tags:

views:

140

answers:

5

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

A: 

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

Will
how do i write that? its the rounding part i don't know how to
Tuffy G
+1  A: 

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
@Tuffy G: That's just a random number I plucked out of my head, replace it with the number you want to round to the nearest `.10`.
Andy E
@Tuffy G: Maybe my edit will help you understand better?
Andy E
Thats done.is there a way i can make it show minnimum 2.80
Tuffy G
@Tuffy G: You can use `Math.max()` method. I added an example to my answer.
Andy E
how would i write that?i'm sorry to sound like complete noob
Tuffy G
A: 
var miles = dist/1609.344
miles = Math.round(miles*10)/10;
miles = miles < 2.80 ? 2.80 : miles;
Matthew Flaschen
+3  A: 
var number = 123.123;

Math.max( Math.round(number * 10) / 10, 2.8 ).toFixed(2);
J-P
+4  A: 

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

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