client budget

How And When To Ask Clients What Their Budget Is

March 7, 2022
ubuntu

Help! I’ve Had To SSH Into A Linux Box And Don’t Know What To Do

April 5, 2022

Many Ways To Skin A Cat – If A Cat Was A String Value

March 28, 2022 / Werner Bestbier

Ways to convert a string to a number.

 

  1. ParseInt()

ParseInt allows for spaces. One downside is that a decimal number passed in will be rounded off to the nearest decimal point and converted to a number.

string to number conversion

 

  1. Number()

Number() could be used instead of parseInt() because it can convert a decimal number without rounding it down. Returns NAN when value cannot be converted.

string to number conversion

 

  1. The Unary Operator

Add the plus operator before any string value and it will be converted to a number.

string to number conversion

 

  1. ParseFloat()

Works better with decimal numbers. Will return NAN if conversion is not possible and only converts the first number when multiple string values are passed in.

string to number conversion

 

  1. floor()

Using Math.floor() also isn’t kind to decimal conversions because it returns the largest number less than or equals to the number passed in.

string to number conversion

 

  1. Multiplication

Simply multiplying your string with 1, converts it to a number. It’s also decimal friendly.

string to number conversion

 

  1. Double Tilde

A double tilde (~~) works the same as the unary operator (+), except it will round down any decimal number.

string to number conversion

Happy coding 🙂

Share

Werner Bestbier

Werner is a front-end developer with a background in design. Making a users web-surfing life easy is his game. His preferred language/framework is Javascript and Angular.

✕
Many Ways To Skin A Cat – If A Cat Was A String Value
This website uses cookies to improve your experience. By using this website you agree to our Data Protection Policy.
Read more