I am trying to convert numbers in following formats
0 -> 0.00
1 -> 1.00
1.1 -> 1.10
4.0 -> 4.00
But problem is its returning as string only
value = 0;
var s = Math.floor(value / 60) + "." + (value % 60 ? value % 60 : '00');
console.log(s+s); //just checking if its number
But its returning as string , I tried parseInt , but its returning only 0 . I tried ParseFloat and fixedTo(2
) , its returning as string only.
I am trying to convert numbers in following formats
0 -> 0.00
1 -> 1.00
1.1 -> 1.10
4.0 -> 4.00
But problem is its returning as string only
value = 0;
var s = Math.floor(value / 60) + "." + (value % 60 ? value % 60 : '00');
console.log(s+s); //just checking if its number
But its returning as string , I tried parseInt , but its returning only 0 . I tried ParseFloat and fixedTo(2
) , its returning as string only.
- 1 If you format a number for display it bees a string. There's no other way. – Álvaro González Commented May 25, 2017 at 7:20
- @Rajesh : it returns string – Vishnu Commented May 25, 2017 at 7:22
-
0
and0.00
are literals representing the same number value. You cannot get a Number literal by definition; only a string. It's not clear, though, what exactly you're trying to do here. – raina77ow Commented May 25, 2017 at 7:24 -
You can convert the string into number using the
Number
function i.e. Number('1.10') return 1.1 as number, but you cannot maintain the format you want. – Max Commented May 25, 2017 at 7:25 - why do you need this kind of "numbers"? – Nina Scholz Commented May 25, 2017 at 7:26
1 Answer
Reset to default 11As seen in the ments, there is no way for that in JavaScript. Formatting a Number always returns a Srting. For this you have some possibilities, though
Number(1).toFixed(2) // "1.00" - setting the number of digits after the decimal point
Number(1).toPrecision(2) // "1.0" - setting the number of digits
These are for printing it out, so normally, it shouldn't matter if it is a String or a Number.
Then if you want to use it as a Number, you just follow @Max 's advice and convert it using the function Number(str)
or the shorthand +str
.