Jayaraj PS
Jayaraj PS

Reputation: 195

Convert negative number in string to negative decimal in JavaScript

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.

Upvotes: 8

Views: 41012

Answers (5)

Ian Hazzard
Ian Hazzard

Reputation: 7771

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!

Upvotes: 2

Muhammad Umer
Muhammad Umer

Reputation: 18097

the shortcut is this:

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

Upvotes: 1

jmrah
jmrah

Reputation: 6222

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

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816364

Simply pass it to the Number function:

var num = Number(str);

Upvotes: 4

Grice
Grice

Reputation: 1375

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

Upvotes: 19

Related Questions