How Do I Convert An Integer To A Float In JavaScript?
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
Solution 1:
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).
Solution 2:
toFixed(x) isn't crossed browser solution. Full solution is following:
function intToFloat(num, decPlaces) { return num + '.' + Array(decPlaces + 1).join('0'); }
Solution 3:
If you don't need (or not sure about) fixed number of decimal places, you can just use
xAsString = (Number.isInteger(x)) ? (x + ".0") : (x.toString());
This is relevant in those contexts like, you have an x
as 7.0
but x.toString()
will give you "7"
and you need the string as "7.0"
. If the x happens to be a float value like say 7.1
or 7.233
then the string should also be "7.1"
or "7.233"
respectively.
Without using Number.isInteger() :
xAsString = (x % 1 === 0) ? (x + ".0") : (x.toString());
Post a Comment for "How Do I Convert An Integer To A Float In JavaScript?"