Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中舍入到小数点后1位?(How do you round to 1 decimal place in Javascript?)

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

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

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

(我尝试了* 10,舍入,/ 10,但是它在int末尾保留了两位小数。)

  ask by Walker translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(Math.round( num * 10) / 10可以工作,这是一个示例...)

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

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

(如果您希望它有一个小数位,即使那是0,也可以添加...)

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!

EDIT: 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;
}

... usage ...

(...用法...)

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

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

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

round(12345.6789) // 12346

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

(...并可以四舍五入到最接近的10或100等...)

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

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

(...并且可以与toFixed组合以一致地格式化为字符串...)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...