21

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 appreciated

Andy E
  • 338,112
  • 86
  • 474
  • 445
Tuffy G
  • 1,521
  • 8
  • 31
  • 42

7 Answers7

33
var number = 123.123;

Math.max( Math.round(number * 10) / 10, 2.8 ).toFixed(2);
James
  • 109,676
  • 31
  • 162
  • 175
8

If you need to round up, use Math.ceil:

Math.max( Math.ceil(number2 * 10) / 10, 2.8 )
Modery
  • 402
  • 2
  • 9
4

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);
Andy E
  • 338,112
  • 86
  • 474
  • 445
2

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);
Seph Reed
  • 8,797
  • 11
  • 60
  • 125
1
var miles = dist/1609.344
miles = Math.round(miles*10)/10;
miles = miles < 2.80 ? 2.80 : miles;
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
0

to round to nearest 0.10 you can multiply by 10, then round (using Math.round), then divide by 10

Will
  • 73,905
  • 40
  • 169
  • 246
0

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)
Tyler
  • 28,498
  • 11
  • 90
  • 106