简体   繁体   English

如何在JavaScript中将整数转换为浮点数?

[英]How do I convert an integer to a float in JavaScript?

I've got an integer (eg 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…

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). 你可以在这里测试它 (虽然我重命名了这个函数,因为它不是一个准确的描述)。

toFixed(x) isn't crossed browser solution. toFixed(x)不是交叉浏览器解决方案。 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" . 这与上下文相关,例如,你有一个x7.0x.toString()会给你"7" ,你需要字符串为"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恰好是像7.17.233这样的浮点值,则字符串也应分别为"7.1""7.233"

Without using Number.isInteger() : 不使用Number.isInteger():

xAsString = (x % 1 === 0) ? (x + ".0") : (x.toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM