Your question can be interpreted as partially vague and very specific at the same time. Meaning that I'm not sure if you are asking specifically about the numbers 5142.37 and 5150 or if you are asking about any double.
Regarding the numbers you quoted--here is an idea (code not compiled or tested):
RoundedNumber = (MathFloor(5142.37 / 10) + 1) * 10;
The above code is just an example to give you some ideas about how to go from a very specific question (about the numbers 5142.37 and 5150) to a more general answer (how to round a double to the nearest 10).
- Rounding to the nearest int makes no sense. Would be 5142
- Rounding to the nearest 5 or 10 makes no sense. Would be 5140.
- Rounding to the nearest 25 or 50 would both be 5150.
double x = MathNearest(5142.37, 25); // x=5150 : double MathNearest(double v, double to){ return to * MathRound(v / to); }
- Thirteen:Your code rounds up, not rounds, and fails on an exact value: MathFloor(5150 / 10) + 1) * 10 = 5160
RoundedNumber = (MathFloor(5142.37 / 10) + 1) * 10;
- Rounding to the nearest int makes no sense. Would be 5142
- Rounding to the nearest 5 or 10 makes no sense. Would be 5140.
- Rounding to the nearest 25 or 50 would both be 5150.
- Thirteen:Your code rounds up, not rounds, and fails on an exact value: MathFloor(5150 / 10) + 1) * 10 = 5160
RoundedNumber = (MathFloor(5142.37 / 10) + 1) * 10;
@WHRoder:
Not quite sure how you come up with 5160.
- 5142.37 / 10 = 514.237
- MathFloor(514.237) = 514
- 514 + 1 = 515
- 515 * 10 = 5150
Thirteen: Not quite sure how you come up with 5160.
|
Fails on an exact value: MathFloor(5150 / 10) + 1) * 10 = 5160 5142.37 is not an exact value. 5150 is.
|
@WHRoeder
Ahhh, I see what you mean...yes, you are right. An exact value at the high end would round up, rather than staying the same.
I like your MathNearest() function. I think two additional companion functions would also be good:
double MathRoundDown(double v, double to){ return to * MathFloor(v / to); } double MathRoundUp(double v, double to){ return to * MathCeil(v / to); }
Examples:
- MathNearest(5142.37, 25) = 5150
- MathRoundUp(5142.37, 10) = 5150

- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
Hi all, could you indicate a system to round the number 5142.37 to 5150 ?
Thank you!