你如何在Javascript中舍入到小数点后1位? [英] How do you round to 1 decimal place in Javascript?

查看:119
本文介绍了你如何在Javascript中舍入到小数点后1位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你可以将javascript中的数字舍入到小数点后的1个字符(正确舍入)吗?

Can you round a number in javascript to 1 character after the decimal point (properly rounded)?

我尝试了* 10,圆形,/ 10但它离开了在int的末尾有两位小数。

I tried the *10, round, /10 but it leaves two decimals at the end of the int.

推荐答案

Math.round(num * 10)/ 10 有效,这是一个例子......

Math.round( num * 10) / 10 works, here is an example...

var number = 12.3456789;
var rounded = Math.round( number * 10 ) / 10;
// rounded is 12.3

如果你想让它有一个小数位,即使这将是0,然后添加...

if you want it to have one decimal place, even when that would be a 0, then add...

var fixed = rounded.toFixed(1);
// fixed is always to 1dp
// BUT: returns string!

// to get it back to number format
parseFloat( number.toFixed(2) )
// 12.34
// but that will not retain any trailing zeros

// so, just make sure it is the last step before output,
// and use a number format during calculations!



编辑:使用精确函数添加循环...



使用这个原理,作为参考,这是一个方便的小圆函数,需要精确... ...

add round with precision function...

Using this principle, for reference, here is a handy little round function that takes precision...

function round(value, precision) {
    var multiplier = Math.pow(10, precision || 0);
    return Math.round(value * multiplier) / multiplier;
}

...使用...

round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7

...默认为舍入到最接近的整数(精度0)...

... defaults to round to nearest whole number (precision 0) ...

round(12345.6789) // 12346

...并且可以使用舍入到最接近的10或100等......

... and can be used to round to nearest 10 or 100 etc...

round(12345.6789, -1) // 12350
round(12345.6789, -2) // 12300

...并正确处理负数...

... and correct handling of negative numbers ...

round(-123.45, 1) // -123.4
round(123.45, 1) // 123.5

...并且可以与toFixed结合使用格式一致为字符串...

... and can be combined with toFixed to format consistently as string ...

round(456.7, 2).toFixed(2) // "456.70"

这篇关于你如何在Javascript中舍入到小数点后1位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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