Hy guys, I have a case where a want to round the number to exactly two decimal places. I will give an example and what I tried.
Lets say I have 15.07567 To round it up I did:
price = Math.round(15.07567 * 100) / 100;
// and I get 15.08
But this presents a problems if we have digits that end wit 0 (example 15.10) and we want two decimals.
price = Math.round(15.10 * 100) / 100;
//15.1
Hmmm, so I tried to use toFixed()
price = Math.round(15.10 * 100) / 100;
total = price.toFixed(2);
// I get "15.10", that's good but it returns a string and that could present a problem later on for me so I tried to fix this with:
price = Math.round(15.10 * 100) / 100;
total = price.toFixed(2);
Number(total) //or parseFloat(total)
// I get 15.1 and around in circle I go?
As Jordan said. When JavaScript displays the number it'll drop the 0. I'd just store the value as is and when you display it, run it through the .toFixed(2) so that it displays properly. Or even better, find a currency formatter since that seems to be what you're looking to display and use that on the view side.
Here's a nice currency formating script.
Then you can use it an object oriented fashion with this code:
Or if you want to specify the thousands and decimal separators for Europe.
If you want to show the
0
in the right, you need to represent the number in String...Always keep your numbers, when you display them run them through toFixed to get a desired display format, so you'll have a ready value in a string format. Because the method is required and therefore designed for display purposes, the function returns a ready string instead of a number.