JS- toFixed returns a string, but I need a number to 6 digits

Michael Treat picture Michael Treat · Aug 28, 2017 · Viewed 14.7k times · Source

I am working with another codebase that I have no control over, and that I cannot see. I can send it inputs and it will return outputs to me. This codebase also doesn't specify what it is written in, but that doesn't matter since I only need to pass it numbers and it hands me back it's outputted numbers. I only know what the expected inputs and outputs are.

One of the inputs I have to work with requires me to give an input that is exactly 6 decimal places long. Most of my numbers will be well above 6 decimal places, so I can just round or truncate it, but in the event that it is rounded to or randomly happens to be a number like 0.125 or 0.5, I am not able to input the correct number.

For instance, if I have a number like 0.5, that is a valid and legitimate number, but the function I am inputting it to will not accept it and will err out because it is not a number to exactly 6 decimals places like 0.500000 is. I also cannot input a string of "0.500000", as it will also err out since it is looking for a number, not a string.

Is there anyway in native JavaScript maintain a specific precision on a number, even if there are extra dead zeros on the end of it?

Examples:

(1/2).toFixed(6) === "0.500000" // the toFixed() function returns a *String*, not a *Number*.

(1/2).toFixed(6) /1 === 0.5 // dividing by 1 coerces it to a Number, but drops the decimals back off the end.

Number( (1/2).toFixed(6) ) === 0.5 // Trying to convert it into a Number using the Number Constructor does the same as  the example above it.

*EDIT: To be clear, I need a Number to 6 decimal places, not a String.

Answer

joe hoeller picture joe hoeller · May 3, 2019

Try this:

parseFloat(val.toFixed(6))