Question

I have the problem that when i round a number to 2 decimals the parseFloat() function removes .00 from the number. I have tried

var num = parseFloat(Math.round(19 * 100) / 100).toFixed(2);

The return: num="19.00"

The return i need: num = 19.00

I know 19 = 19.00, but i am using a service that always require two decimals .00

The function returns a string with the right value. When i parse it to float the .00 is removed.

Was it helpful?

Solution

You cannot get 19.00 as float, only as string, because numbers always remove trailing zeros.

Maybe you can show us a bit more code to get an idea, there you need these trailing zeros?

OTHER TIPS

Numbers do and can not hold information about their representation. They are only a numerical value.

When you display a number using window.alert, console.log or similar, you are not looking at a number, but at a string. Those display functions convert numbers to strings before displaying them. Number.toFixed also converts numbers into strings, with the difference being that it rounds them to two decimal places, so you end up with another representation of the same number.

What I am trying to say is that to display a number, you cannot get around converting it to a string. Whether you do it explicitly or the display function does it for you. When you send the number to the service that you are using, you are probably also sending a string (JSON, XML, etc. are always strings once you send them). If you need the value of the number for calculations, use it, then convert it in the end. No matter how, you have to do it in the end if you want those 0's at the end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top