I've got an integer (e.g. 12), and I want to convert it to a floating point number, with a specified number of decimal places.
Draft
function intToFloat(num, decimal) { [code goes here] } intToFloat(12, 1) // returns 12.0 intToFloat(12, 2) // returns 12.00 // and so on…
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.
The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number.
Javascript has provided a method called parseFloat() to convert a string into a floating point number. Floating numbers are nothing but decimals.
What you have is already a floating point number, they're all 64-bit floating point numbers in JavaScript.
To get decimal places when rendering it (as a string, for output), use .toFixed()
, like this:
function intToFloat(num, decPlaces) { return num.toFixed(decPlaces); }
You can test it out here (though I'd rename the function, given it's not an accurate description).
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