开发者

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 here] }
intToFloat(12, 1) // returns 12.0
intToFloat(12, 2) // returns 12.00
// and so on…


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).


toFixed(x) isn't crossed browser solution. Full solution is following:

function intToFloat(num, decPlaces) { return num + '.' + Array(decPlaces + 1).join('0'); }


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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜