Javascript 向上舍入最接近 0.10
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2206335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
round up nearest 0.10
提问by Tuffy G
I need to round up to the nearest 0.10 with a minimum of 2.80
我需要四舍五入到最接近的 0.10,最小值为 2.80
var panel;
if (routeNodes.length > 0 && (panel = document.getElementById('distance')))
{
panel.innerHTML = (dist/1609.344).toFixed(2) + " miles = £" + (((dist/1609.344 - 1) * 1.20) + 2.80).toFixed(2);
}
any help would be appreciated
任何帮助,将不胜感激
回答by James
var number = 123.123;
Math.max( Math.round(number * 10) / 10, 2.8 ).toFixed(2);
回答by Modery
If you need to round up, use Math.ceil:
如果您需要四舍五入,请使用 Math.ceil:
Math.max( Math.ceil(number2 * 10) / 10, 2.8 )
回答by Andy E
Multiply by 10, then do your rounding, then divide by 10 again
乘以 10,然后进行四舍五入,然后再次除以 10
(Math.round(12.362 * 10) / 10).toFixed(2)
Another option is:
另一种选择是:
Number(12.362.toFixed(1)).toFixed(2)
In your code:
在您的代码中:
var panel;
if (routeNodes.length > 0 && (panel = document.getElementById('distance')))
{
panel.innerHTML = Number((dist/1609.344).toFixed(1)).toFixed(2)
+ " miles = £"
+ Number((((dist/1609.344 - 1) * 1.20) + 2.80).toFixed(1)).toFixed(2);
}
To declare a minimum, use the Math.maxfunction:
要声明最小值,请使用以下Math.max函数:
var a = 10.1, b = 2.2, c = 3.5;
alert(Math.max(a, 2.8)); // alerts 10.1 (a);
alert(Math.max(b, 2.8)); // alerts 2.8 because it is larger than b (2.2);
alert(Math.max(c, 2.8)); // alerts 3.5 (c);
回答by Seph Reed
This is a top hit on google for rounding in js. This answer pertains more to that general question, than this specific one. As a generalized rounding function you can inline:
这是谷歌在 js 中四舍五入的热门话题。这个答案更多地与这个一般问题有关,而不是这个特定的问题。作为广义舍入函数,您可以内联:
const round = (num, grainularity) => Math.round(num / grainularity) * grainularity;
const round = (num, grainularity) => Math.round(num / grainularity) * grainularity;
Test it out below:
下面测试一下:
const round = (num, grainularity) => Math.round(num / grainularity) * grainularity;
const test = (num, grain) => {
console.log(`Rounding to the nearest ${grain} for ${num} -> ${round(num, grain)}`);
}
test(1.5, 1);
test(1.5, 0.1);
test(1.5, 0.5);
test(1.7, 0.5);
test(1.9, 0.5);
test(-1.9, 0.5);
test(-1.2345, 0.214);
回答by Matthew Flaschen
var miles = dist/1609.344
miles = Math.round(miles*10)/10;
miles = miles < 2.80 ? 2.80 : miles;
回答by Will
to round to nearest 0.10 you can multiply by 10, then round (using Math.round), then divide by 10
要舍入到最接近的 0.10,您可以乘以 10,然后舍入(使用Math.round),然后除以 10
回答by Tyler
Round to the nearest tenth:
四舍五入到最接近的十分之一:
Math.max(x, 2.8).toFixed(1) + '0'
Round up:
围捕:
Math.max(Math.ceil(x * 10) / 10, 2.8).toFixed(2)

