将数字截断为两位小数而不进行舍入 [英] Truncate number to two decimal places without rounding

查看:158
本文介绍了将数字截断为两位小数而不进行舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的值为15.7784514,我想将其显示为15.77而没有舍入。

Suppose I have a value of 15.7784514, I want to display it 15.77 with no rounding.

var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));

结果 -

15.8
15.78
15.778
15.7784514000 

如何显示15.77?

推荐答案

将数字转换为字符串,将数字与小数点后第二位匹配:

Convert the number into a string, match the number up to the second decimal place:

function calc(theform) {
    var num = theform.original.value, rounded = theform.rounded
    var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
    rounded.value = with2Decimals
}

<form onsubmit="return calc(this)">
Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" />
<br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly>
</form>

toFixed 方法在某些情况下失败,与 toString 不同,所以要非常小心。

The toFixed method fails in some cases unlike toString, so be very careful with it.

这篇关于将数字截断为两位小数而不进行舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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