[英]Converting Float to 2 Decimal Number in Javascript
我正在尝试将var
转换为 Javascript 中的 2 个小数点数字,如下所示:
var num1 = 9.7000000000
var newNum1= Math.floor(parseFloat(num1) * 100) / 100;
然而,output 结果是9.69
。
我感谢任何帮助或建议。
编辑:谢谢大家,我也试过.toFixed(2)
。
但是,后来我在将它与算术函数一起使用时遇到了问题:
if (weight < newNum1)
已解决:通过添加一元加运算符+
如下:
newNum1= +num1.toFixed(2);
您可以使用.toFixed(2)
和一元加号运算符将字符串转换回数字。
const res = +num1.toFixed(2);//9.7
你试过toFixed
吗?
toFixed()
方法将数字转换为字符串,四舍五入到指定的小数位数。
var num1 = 9.7000000000 var newNum1= num1.toFixed(2) console.log(newNum1)
您可以使用 toFixed() 方法...,
var num1 = 9.7000000000 var newNum1 = num1.toFixed(2); console.log(newNum1);
您可以使用此代码段:
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); console.log(round(9.7000000000, 2));
如果您想“实际”将数字修改为 2 位小数(不仅是显示格式),请使用以下解决方案。 这里的数字实际上是在内部更改为一个新的数字。
如果您使用number.toFixed()方法,您只会将数字显示/显示为 2 位小数,但数字不会更改。 toFixed() 用于格式化。
// Round to the required number of desimal places // @input {number} number to round // {decimals} number of decimal places // @return {float} rounded number function numberRoundDecimal(num, decimals) { return Math.round(num*Math.pow(10,decimals))/Math.pow(10,decimals) } // ------- tests -------- console.log(numberRoundDecimal(9.7000000000,2)) // 9.7 console.log(numberRoundDecimal(-0.024641163062896567,3)) // -0.025 console.log(numberRoundDecimal(0.9993360575508052,3)) // 0.999 console.log(numberRoundDecimal(1.0020739645577939,3)) // 1.002 console.log(numberRoundDecimal(0.999,0)) // 1 console.log(numberRoundDecimal(0.975,0)) // 1 console.log(numberRoundDecimal(0.975,1)) // 1 console.log(numberRoundDecimal(0.975,2)) // 0.98
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.