如何将整数转换为JavaScript中的浮点数? [英] How do I convert an integer to a float in JavaScript?

查看:1866
本文介绍了如何将整数转换为JavaScript中的浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数(例如 12 ),我想将它转换为浮点数小数位数。

汇票

 <$ c $函数intToFloat(num,decimal){[code goes here]} 
intToFloat(12,1)//返回12.0
intToFloat(12,2)//返回12.00
//等等...


解决方案

点数,它们都是JavaScript中的64位浮点数。

要在呈现小数点时获得小数位(作为字符串,输出),请使用 .toFixed() ,像这样:

  function intToFloat(num,decPlaces){return num.toFixed(decPlaces); } 

你可以在这里测试它(尽管我会重命名该函数,因为它不是一个准确的描述)。

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

这篇关于如何将整数转换为JavaScript中的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆