在JavaScript中,当从浮点数转换为字符串时,如何才能在小数点后得到2位数字?例如,0.34而不是0.3445434。
当前回答
var result = Math.round(original*100)/100;
具体细节,以防代码不是自解释的。
编辑:…或者直接使用toFixed,就像Tim Büthe提议的那样。忘记了,谢谢你的提醒(还有点赞):)
其他回答
var result = Math.round(original*100)/100;
具体细节,以防代码不是自解释的。
编辑:…或者直接使用toFixed,就像Tim Büthe提议的那样。忘记了,谢谢你的提醒(还有点赞):)
var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding
有一些函数可以取整数字。例如:
var x = 5.0364342423;
print(x.toFixed(2));
将打印5.04。
编辑: 小提琴
使用toFixed()时要小心:
首先,使用数字的二进制表示来四舍五入,这可能会导致意想不到的行为。例如
(0.595).toFixed(2) === '0.59'
而不是‘0.6’。
其次,toFixed()存在IE错误。在IE中(至少到版本7,没有检查IE8),以下是正确的:
(0.9).toFixed(0) === '0'
遵循kkyy的建议或使用自定义toFixed()函数可能是一个好主意,例如
function toFixed(value, precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(value * power) / power);
}
也许你还需要小数分隔符?这是我刚刚创建的一个函数:
function formatFloat(num,casasDec,sepDecimal,sepMilhar) {
if (num < 0)
{
num = -num;
sinal = -1;
} else
sinal = 1;
var resposta = "";
var part = "";
if (num != Math.floor(num)) // decimal values present
{
part = Math.round((num-Math.floor(num))*Math.pow(10,casasDec)).toString(); // transforms decimal part into integer (rounded)
while (part.length < casasDec)
part = '0'+part;
if (casasDec > 0)
{
resposta = sepDecimal+part;
num = Math.floor(num);
} else
num = Math.round(num);
} // end of decimal part
while (num > 0) // integer part
{
part = (num - Math.floor(num/1000)*1000).toString(); // part = three less significant digits
num = Math.floor(num/1000);
if (num > 0)
while (part.length < 3) // 123.023.123 if sepMilhar = '.'
part = '0'+part; // 023
resposta = part+resposta;
if (num > 0)
resposta = sepMilhar+resposta;
}
if (sinal < 0)
resposta = '-'+resposta;
return resposta;
}
推荐文章
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件