javascript:将浮点数舍入到最接近的.25(或其他...) [英] javascript: rounding a float UP to nearest .25 (or whatever...)

查看:69
本文介绍了javascript:将浮点数舍入到最接近的.25(或其他...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能找到的所有答案都是四舍五入到最接近的值,而不是达到值...例如

All answers I can find are rounding to nearest, not up to the value... for example

1.0005 => 1.25  (not 1.00)
1.9   => 2.00
2.10 => 2.25
2.59 => 2.75   etc.

似乎非常基本,但这让我很难过。
但这必须向上舍入,而不是到最近,这是一件相对容易的事情。

would seem to be pretty basic, but this has me stumped. But this has to round up, not to nearest, which is a relatively easy thing to do.

推荐答案

除以数字 0.25 (或您想要最接近的任何分数)。

Divide the number by 0.25 (or whatever fraction you want to round nearest to).

向上舍入到最接近的整数。

Round up to nearest whole number.

乘以 0.25 的结果。

Math.ceil(1.0005 / 0.25) * 0.25
// 1.25

Math.ceil(1.9 / 0.25) * 0.25
// 2

// etc.

function toNearest(num, frac) {
  return Math.ceil(num / frac) * frac;
}

var o = document.getElementById("output");

o.innerHTML += "1.0005 => " + toNearest(1.0005, 0.25) + "<br>";
o.innerHTML += "1.9 => " + toNearest(1.9, 0.25) + "<br>";
o.innerHTML += "2.10 => " + toNearest(2.10, 0.25) + "<br>";
o.innerHTML += "2.59 => " + toNearest(2.59, 0.25);

<div id="output"></div>

这篇关于javascript:将浮点数舍入到最接近的.25(或其他...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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