javascript:将浮点数四舍五入到最接近的 .25(或其他什么..)
javascript: rounding a float UP to nearest .25 (or whatever...)
我能找到的所有答案都是四舍五入到最接近的,而不是接近的值......例如
1.0005 => 1.25 (not 1.00)
1.9 => 2.00
2.10 => 2.25
2.59 => 2.75 etc.
这似乎是很基本的,但这让我难倒了。但这必须四舍五入,而不是接近,这是一件相对容易的事情。
将
数字除以0.25
(或您想要四舍五入到的最接近的任何分数)。
向上舍入到最接近的整数。
将结果乘以 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>
将数字乘以 4,对结果使用 Math.ceil,然后将该数字除以 4。
只需乘
以 4 并取 4 倍的 ceiled 值。
var values = [1.0005, 1.9, 2.10, 2.59],
round = values.map(function (a) { return Math.ceil(a * 4) / 4; });
document.write('<pre>' + JSON.stringify(round, 0, 4) + '</pre>');
其他除法和乘法不适用于某些值,例如 1.59 您可以尝试自定义圆角函数
function customRound(x) {
var rest = x - Math.floor(x)
if (rest >= 0.875) {
return Math.floor(x) + 1
} else if (rest >= 0.625) {
return Math.floor(x) + 0.75
} else if (rest >= 0.375) {
return Math.floor(x) + 0.50
} else if (rest >= 0.125){
return Math.floor(x) + 0.25
} else {
return Math.floor(x)
}
}
相关文章:
- 是什么让一个“;Uncaught RangeError:超过了最大调用堆栈大小“;错误(Chrome,在其他浏览器中显示
- 什么's导致了512字节的限制-openkeyval或其他什么
- 杜兰达尔默认路线有效,其他什么都没有
- javascript或缓存错误?或者其他什么
- 在IE8和其他带有javascript的浏览器中获取正文类的标准解决方案是什么
- 如果React.js是V,那么在MVC中,其他字母是什么
- document.write和document.innerHTML以及其他javascript问题之间有什么区别
- 如何上传文件不使用多部分编码?(可能使用八位字节或其他什么)
- @internal react 代码中的 JavaScript 文档标签,是 jsdoc、闭包还是其他什么
- 如何匹配其他一切,但不管它是什么's与regex匹配
- Javascript 我应该使用什么其他技巧来代替导出符号
- javascript:将浮点数四舍五入到最接近的 .25(或其他什么..)
- 在我的测试脚本中,我运行了 if 语句,但我从未运行过其他语句?我做错了什么
- 什么是原型?构造函数或其他对象
- 在默认情况下将可枚举设置为 false 的 JS 中创建对象属性的其他方法是什么
- 如何检测客户端´s的计算机语言/或其他什么,以便自动更改网站中的语言
- javascript+jquery检查元素是否存在,然后设置其值,或者其他什么
- 在浏览器中实现类似Powerpoint的应用程序-Javascript、Silverlight或其他什么
- <noscript>或者其他什么
- 变量范围或其他什么?刚开始的JS