最接近0.10

时间:2010-02-05 09:54:14

标签: 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) + 2.80).toFixed(2); 
 }

任何帮助将不胜感激

7 个答案:

答案 0 :(得分:30)

var number = 123.123;

Math.max( Math.round(number * 10) / 10, 2.8 ).toFixed(2);

答案 1 :(得分:7)

如果您需要向上舍入,请使用Math.ceil:

Math.max( Math.ceil(number2 * 10) / 10, 2.8 )

答案 2 :(得分:3)

乘以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);

答案 3 :(得分:1)

var miles = dist/1609.344
miles = Math.round(miles*10)/10;
miles = miles < 2.80 ? 2.80 : miles;

答案 4 :(得分:1)

这是在js中四舍五入在Google上的热门话题。这个答案比这个具体问题更与那个一般性问题有关。作为通用的舍入函数,您可以内联:

const round = (num, grainularity) => Math.round(num / grainularity) * grainularity;

在下面对其进行测试:

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);

答案 5 :(得分:0)

要舍入到最接近的0.10,你可以乘以10,然后舍入(使用Math.round),然后除以10

答案 6 :(得分:0)

舍入到最近的第十位:

Math.max(x, 2.8).toFixed(1) + '0'

总结:

Math.max(Math.ceil(x * 10) / 10, 2.8).toFixed(2)