Let me give you an example.
var a = 2.0;
var stringA = "" + a;
I will get: stringA = "2"
, but I want: stringA = "2.0"
.
I don't want to lose precision however, so if:
var b = 2.412;
var stringB = "" + b;
I want to get the standard: stringB = "2.412"
.
That's why toFixed()
won't work here. Is there any other way to do it, than to explicitly check for whole numbers like this?:
if (a % 1 === 0)
return "" + a + ".0";
else
return "" + a;
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With