round up nearest 0.10
I need to round up to the nearest 0.10 with a minimum of 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 appreciate开发者_JS百科d
var number = 123.123;
Math.max( Math.round(number * 10) / 10, 2.8 ).toFixed(2);
If you need to round up, use Math.ceil:
Math.max( Math.ceil(number2 * 10) / 10, 2.8 )
Multiply by 10, then do your rounding, then divide by 10 again
(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.max
function:
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);
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:
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);
var miles = dist/1609.344
miles = Math.round(miles*10)/10;
miles = miles < 2.80 ? 2.80 : miles;
to round to nearest 0.10 you can multiply by 10, then round (using Math.round
), then divide by 10
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)
精彩评论