如何 JavaScript 向下舍入数字 - 继续

发布于 2024-11-04 18:14:40 字数 449 浏览 0 评论 0原文

这与我之前的问题有点不同

How to round up using javascript

我有这组数字并希望四舍五入到小数点后一位。由于标准的javascript舍入功能无法满足我的要求,希望有人可以帮助我:)

以下是舍入时所需的输出:

192.168 => 192.10
192.11=> 192.10
192.21 =>192.20
192.26=> 192.20
192.30=> 192.30

This is a bit different from my question before

How to round up using javascript

I have this set of number and want to round down to 1 decimal point. Since standard javascript round up function cant meet my requirement, hope someone can help me :)

Below is the ouput needed when round down:

192.168 => 192.10
192.11 => 192.10
192.21 =>192.20
192.26 => 192.20
192.30 = > 192.30

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

像你 2024-11-11 18:14:40

这不是四舍五入,
192.168 四舍五入到小数点后两位是 192.20。

但是根据您的要求:
您可能只想将其乘以 10 的倍数,取 'floor' ,然后除以相同的数字。

在这里查看:http://jsfiddle.net/7qeGH/

var numbers = new Array(192.168,192.11 ,192.21 ,192.26 ,192.30 );

var response = "";

for(var i =0 ; i< numbers.length ; i++)

{
     var rounded = Math.floor(numbers[i]*10)/10  + '0';  // '0' is added as string
     response +=   numbers[i] + " => " + rounded + "\n";

}

alert(response);

this is not rounding,
192.168 rounded to two decimal places is 192.20.

However for your requirement :
You might just want to multiply it by multiples of 10, take 'floor' , and then divide by same number.

see it here : http://jsfiddle.net/7qeGH/

var numbers = new Array(192.168,192.11 ,192.21 ,192.26 ,192.30 );

var response = "";

for(var i =0 ; i< numbers.length ; i++)

{
     var rounded = Math.floor(numbers[i]*10)/10  + '0';  // '0' is added as string
     response +=   numbers[i] + " => " + rounded + "\n";

}

alert(response);
余厌 2024-11-11 18:14:40

Math.round(number * 10) / 10 怎么样?您将得到小数点后 1 位的结果,因此您可以在末尾添加零 (Math.round(number * 10) / 10) + "0"

但实际上您是向下舍入而不是向上舍入。所以它会是Math.floor()。

How about Math.round(number * 10) / 10 ? You'll get a result with 1 decimal so you can add a zero at the end (Math.round(number * 10) / 10) + "0"

But actually you round down not up. So it would be Math.floor().

凶凌 2024-11-11 18:14:40

你可以尝试这样的事情:

var mynum = 192.168;
var result=Math.round(mynum*100)/100; 

You can try something like this :

var mynum = 192.168;
var result=Math.round(mynum*100)/100; 
鲸落 2024-11-11 18:14:40

很简单

testVal = Math.round(YourNumberHere*100)/100 ;

Very simple

testVal = Math.round(YourNumberHere*100)/100 ;
聚集的泪 2024-11-11 18:14:40

你不就是想打地板吗?即“向下舍入”。

Math.floor(the_number*10)/ 10)

Aren't you simply trying to floor? That is, "round down".

Math.floor(the_number*10)/ 10)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文