Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding integers to nearest multiple of 10 [duplicate]

I am trying to figure out how to round prices - both ways. For example:

Round down 43 becomes 40 143 becomes 140 1433 becomes 1430  Round up 43 becomes 50 143 becomes 150 1433 becomes 1440 

I have the situation where I have a price range of say:

£143 - £193 

of which I want to show as:

£140 - £200 

as it looks a lot cleaner

Any ideas on how I can achieve this?

like image 511
dhardy Avatar asked Mar 01 '13 09:03

dhardy


People also ask

How do you round to the nearest multiple of 10?

To round off a number to the nearest tens, we round off it to the nearest multiple of ten. 78 is situated between 70 and 80. The middle of 70 and 80 is 75. 78 is nearer to 80 and farther from 70.

How do you round a number to the nearest multiple?

The MROUND function rounds a number to the nearest given multiple. The multiple to use for rounding is provided as the significance argument. If the number is already an exact multiple, no rounding occurs and the original number is returned.

How do you find the nearest multiple of 10 in python?

Python – Round Number to Nearest 10 To round number to nearest 10, use round() function. We can divide the value by 10, round the result to zero precision, and multiply with 10 again. Or you can pass a negative value for precision.


2 Answers

I would just create a couple methods;

int RoundUp(int toRound) {      if (toRound % 10 == 0) return toRound;      return (10 - toRound % 10) + toRound; }  int RoundDown(int toRound) {     return toRound - toRound % 10; } 

Modulus gives us the remainder, in the case of rounding up 10 - r takes you to the nearest tenth, to round down you just subtract r. Pretty straight forward.

like image 139
evanmcdonnal Avatar answered Oct 05 '22 23:10

evanmcdonnal


You don't need to use modulus (%) or floating point...

This works:

public static int RoundUp(int value) {     return 10*((value + 9)/10); }  public static int RoundDown(int value) {     return 10*(value/10); } 
like image 28
Matthew Watson Avatar answered Oct 06 '22 01:10

Matthew Watson