限制在小数点后面显示的数字的数量 [英] Limit the amount of number shown after a decimal place in javascript

查看:199
本文介绍了限制在小数点后面显示的数字的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

干草,我有一些像这样的花车

  4.3455 
2.768
3.67

我想以这样的方式显示它们

  4.34 
2.76
3.67

要把数字向上或向下舍入,只需将小数点后面显示的数字量限制为2。正在寻找 toFixed

  var x = 4.3455; 
alert(x.toFixed(2)); //警报4.35 - 不是你想要的!

...但是看起来像是要截断而不是舍入,所以:

  var x = 4.3455; 
x = Math.floor(x * 100)/ 100;
alert(x.toFixed(2)); // alert 4.34


Hay, i have some floats like these

4.3455
2.768
3.67

and i want to display them like this

4.34
2.76
3.67

I don't want to round the number up or down, just limit the amount of numbers shown after the decimal place to 2.

解决方案

You're looking for toFixed:

var x = 4.3455;
alert(x.toFixed(2)); // alerts 4.35 -- not what you wanted!

...but it looks like you want to truncate rather than rounding, so:

var x = 4.3455;
x = Math.floor(x * 100) / 100;
alert(x.toFixed(2)); // alerts 4.34

这篇关于限制在小数点后面显示的数字的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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