Reputation: 17522
I need to parse a string to (2) decimal points.
like so:
console.log("12345.6789"); // return 12345.67
The problem I am facing is that if the decimals are .00
the numbers (decimals) are removed and a whole number is return instead.
console.log(parseFloat("123.00"))// return 123 // expected 123.00
console.log(parseFloat("123.01"))// return 123.01 // expected 123.01
If you are wondering why should this matter? It's because I need to present the data so it's very easy to scan for humans.
e.g: below is not pretty or easy to read (especially when text is align to the right) and we enter into the thousands and millions etc...
123.23
123,456.46
123
123,956.01
145
135.02
I need it to be like so: 123.23 123.46 123.00 123.01 145.00 135.02
Also the typeof
should not be a string but an actual number.
123.00 // correct
"123.00"// incorrect // (I can use .tofixed() so this is not useful )
Upvotes: 1
Views: 264
Reputation: 48212
Like others have already said, the toFixed()
function will take care of the fractional part.
If you also want to add thousand separator for readability, you can use a simple regex as described here.
var d = ... // <-- this is a number
var str = d.toFixed(2)
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
// ^-- use this "replace()" to add thousand separators
See, also, this short demo.
Upvotes: 0
Reputation: 15387
Try this
If value is text type:
parseFloat("123.456").toFixed(2);
If value is number:
var numb = 123.23454;
numb = numb.toFixed(2);
Upvotes: 0
Reputation: 5822
If you print to the console
console.log( (123).toFixed( 2 ) ); // outputs "123.00"
However, the quotes around the output are just to illustrate the fact that it is a string. It should be fine to use .toFixed()
.
Upvotes: 0
Reputation: 21367
This does not the work the way you try it. You want a string. Indisputably, 3.00
is the same as 3
if you save it as a number and printing will make no difference. You want to manually add the "0"s and therefore you have to create a string.
.tofixed() is perfectly fine for this use. If you print stuff, it is converted to a string anyway.
Upvotes: 0