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.

2

5 Answers 5

19

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

Sign up to request clarification or add additional context in comments.

1 Comment

@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
4

Simply pass it to the Number function:

var num = Number(str);

1 Comment

Number function only works if the number does not have any other, not a number string. if you have a '-10%' Number resolve NA
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!

Comments

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

Comments

1

the shortcut is this:

"-3.30" <--- the number in string form
+"-3.30" <----Add plus sign
-3.3 <----- Number in number type. 

1 Comment

It keeps the decimal fraction and the sign, and it appears to be the fastest in Chrome: 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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.