There is a built-in function for this.
var a = 2;
var b = a.toFixed(1);
This rounds the number to one decimal place, and displays it with that one decimal place, even if it's zero.
Answer from Niet the Dark Absol on Stack OverflowVideos
There is a built-in function for this.
var a = 2;
var b = a.toFixed(1);
This rounds the number to one decimal place, and displays it with that one decimal place, even if it's zero.
If you want to append .0 to output from a Number to String conversion and keep precision for non-integers, just test for an integer and treat it specially.
function toNumberString(num) {
if (Number.isInteger(num)) {
return num + ".0"
} else {
return num.toString();
}
}
Input Output
3 "3.0"
3.4567 "3.4567"
If they're meant to be separate values, try this:
var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])
If they're meant to be a single value (like in French, where one-half is written 0,5)
var value = parseFloat("554,20".replace(",", "."));
Have you ever tried to do this? :p
var str = '3.8';ie
alert( +(str) + 0.2 );
+(string) will cast string into float.
Handy!
So in order to solve your problem, you can do something like this:
var floatValue = +(str.replace(/,/,'.'));
Edit: I got the answer I needed below (multiplying by a power of ten, rounding, and then dividing again by the same power of ten appears to do the trick)
Is there any library out there that will a clean up floats (the results of a prior sequence of calculations)? For example:
1.24999999993 -> 1.25
2.99999999998 -> 3
-0.37499999982 -> -0.375 etc
I realize I can do +float.toFixed(precision), where precision is something like 6-9 to get a decent result, but I’m wondering if there is something out there that is more systematic and doesn’t rely on strings.
I tried decimal.js and it’s a mess because it would require me having to rewrite everything to handle its Decimal class, and in the end all of its presentation methods just convert the float values to strings anyway, so I’m better off just doing toFixed() and coercing back to a number instead of bringing in a whole library to use one method that does the same but only goes halfway.
Basically I’m just looking for a lightweight library or function someone has written that cleans up floats as numbers. Or is it just not possible without using intermediate strings in some way?
I tried googling for this already obviously, without any luck. Just lots of the same article and question about floating point inconsistencies in JS and other languages.