Javascript 四舍五入最接近0.10
我需要四舍五入到最接近的0.10,最小值为2.80Javascript 四舍五入最接近0.10,javascript,Javascript,我需要四舍五入到最接近的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)
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);
}
任何帮助都将不胜感激。若要四舍五入到最接近的0.10,您可以乘以10,然后四舍五入(使用
Math.round
),然后除以10。乘以10,然后进行四舍五入,然后再除以10
(Math.round(12.362 * 10) / 10).toFixed(2)
另一个选择是:
Number(12.362.toFixed(1)).toFixed(2)
在代码中:
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);
}
要声明最小值,请使用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);
var miles=dist/1609.344
英里=数学圆(英里*10)/10;
英里=英里<2.80?2.80英里;
如果您需要对进行取整,请使用Math.ceil:
Math.max( Math.ceil(number2 * 10) / 10, 2.8 )
四舍五入到最接近的十分之一:
Math.max(x, 2.8).toFixed(1) + '0'
综述:
Math.max(Math.ceil(x * 10) / 10, 2.8).toFixed(2)
这是谷歌在js中取整的热门话题。这个答案更多的是关于那个一般性问题,而不是这个具体问题。作为通用舍入函数,您可以内联:
const round=(num,grainularity)=>Math.round(num/grainularity)*grainularity代码>
在下面进行测试:
const round=(num,grainularity)=>Math.round(num/grainularity)*grainularity;
常量测试=(数值,粒度)=>{
log(${num}->${round(num,grain)}`)的${grain}舍入到最近的${grain});
}
试验(1.5,1);
试验(1.5,0.1);
试验(1.5,0.5);
试验(1.7,0.5);
试验(1.9,0.5);
测试(-1.9,0.5);
测试(-1.2345,0.214)代码>如何编写?这是圆的部分我不知道怎么做to@TuffyG:那只是我从脑袋里拔出的一个随机数,用你想四舍五入到最近的.10
@Tuffy G:你可以使用Math.max()
方法。我在回答中加了一个例子,我该怎么写呢?我很抱歉听起来像个彻头彻尾的傻瓜
Math.max(x, 2.8).toFixed(1) + '0'
Math.max(Math.ceil(x * 10) / 10, 2.8).toFixed(2)