8

I have a string : "-10.456" I want to convert it to -10.465 in decimal (using JavaScript) so that I can compare for greater than or lesser than with another decimal number.

Regards.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Jayaraj PS
  • 195
  • 1
  • 4
  • 18
  • 2
    possible duplicate of [How do I Convert a String into an Integer in JavaScript?](http://stackoverflow.com/questions/1133770/how-do-i-convert-a-string-into-an-integer-in-javascript) – Mike Ante Oct 24 '14 at 16:07
  • 2
    Related: [How to convert string into float in javascript?](http://stackoverflow.com/q/642650/218196) – Felix Kling Oct 24 '14 at 16:10

5 Answers5

18

The parseInt function can be used to parse strings to integers and uses this format: parseInt(string, radix);

Ex: parseInt("-10.465", 10); returns -10

To parse floating point numbers, you use parseFloat, formatted like parseFloat(string)

Ex: parseFloat("-10.465"); returns -10.465

Community
  • 1
  • 1
Grice
  • 1,345
  • 11
  • 24
  • @Grice what if I am trying to add two decimal the trailing zeros are missing! +(parseFloat(3.6 + 4.4).toFixed(1)) if I use .toFixed it returns string and parseFloat return number but without decimal point/trailing zero – Santosh Jan 07 '19 at 19:06
4

Simply pass it to the Number function:

var num = Number(str);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Number function only works if the number does not have any other, not a number string. if you have a '-10%' Number resolve NA – xzegga May 31 '22 at 16:36
2

Here are two simple ways to do this if the variable str = "-10.123":

#1

str = str*1;

#2

str = Number(str);

Both ways now contain a JavaScript number primitive now. Hope this helps!

Ian Hazzard
  • 7,661
  • 7
  • 34
  • 60
1

In javascript, you can compare mixed types. So, this works:

var x = "-10.456";
var y = 5.5;
alert(x < y) // true
alert(x > y) // false
jmrah
  • 5,715
  • 3
  • 30
  • 37
1

the shortcut is this:

"-3.30" <--- the number in string form
+"-3.30" <----Add plus sign
-3.3 <----- Number in number type. 
Muhammad Umer
  • 17,263
  • 19
  • 97
  • 168
  • 1
    It keeps the decimal fraction and the sign, and it appears to be the fastest in Chrome: http://jsperf.com/number-vs-plus-vs-toint-vs-tofloat/14 (note: some of the tests convert to int!). You can also use a minus instead of a plus to negate the number. It even supports e-notation! (`+"12.34e5"`) I don't understand why no one upvoted this. Are there portability issues? – CodeManX Sep 01 '15 at 22:08