如何在 JavaScript 中将整数转换为浮点数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4293230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert an integer to a float in JavaScript?
提问by nyuszika7h
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.
我有一个整数(例如12),我想将其转换为浮点数,并具有指定的小数位数。
Draft
草案
function intToFloat(num, decimal) { [code goes here] }
intToFloat(12, 1) // returns 12.0
intToFloat(12, 2) // returns 12.00
// and so on…
回答by Nick Craver
What you have is already a floating point number, they're all 64-bit floating point numbers in JavaScript.
你所拥有的已经是一个浮点数,它们都是 JavaScript 中的 64 位浮点数。
To get decimal places when rendering it (as a string, for output), use .toFixed()
, like this:
要在渲染时获取小数位(作为字符串,用于输出),请使用.toFixed()
,如下所示:
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).
你可以在这里测试它(尽管我会重命名该函数,因为它不是一个准确的描述)。
回答by simonbor
toFixed(x) isn't crossed browser solution. Full solution is following:
toFixed(x) 不是跨浏览器解决方案。完整的解决方案如下:
function intToFloat(num, decPlaces) { return num + '.' + Array(decPlaces + 1).join('0'); }
回答by Sachin Murali G
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.
这在那些上下文中是相关的,例如,你有一个x
as7.0
但x.toString()
会给你"7"
,你需要字符串 as "7.0"
。如果 x 恰好是像 say 7.1
or7.233
这样的浮点值,那么字符串也应该是"7.1"
or "7.233"
。
Without using Number.isInteger() :
不使用 Number.isInteger() :
xAsString = (x % 1 === 0) ? (x + ".0") : (x.toString());