How to Round to Arbitrary Precision in any Programming Language: Multiply your rounding number by 10^y where *y* is the precision to round to. Call your language’s built-in round() method on this number. Divide the result by 10^y. Easy peasy. It also makes it easier to implement different rounding methods because you’re always dealing with the digit at the same location in the number.

In javascript:

1 2 3 4 5 6 7 |
function round(x, y) { var p = Math.pow(10, y)); x *= p; x = Math.round(x); x /= p; return x; } |

Then there’s Math.round() which you may not have or may not want to use and, if you’re rounding, at all, you’ll inevitably find yourself looking at various rounding methods. Since Math.round(), and usually all default round() methods in most programming languages, use traditional “half up” rounding, you may find you need a different method, like banker’s rounding which is “half to even”.

To accomplish a different rounding method, create your own round() function, apply the appropriate power to your number. Then, subtract the integer portion of the number. You are left with the fraction portion of your number: This gives you the rounding digit as your final number. With this number, you can then decide whether to truncate the original number or add 1. Once you’re done that, you can then remove the power manipulation you did in the first step and now you’re left with the final rounded number.

In javascript:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// x: number to round // precision: Positive number indicates the position of // the rounding digit after the decimal place. // Negative number indicates the position of // the rounding digit before the decimal place. function roundEven( x, precision ) { x *= Math.pow(10, precision); var originalX = x; x -= Math.floor(x); if ( x < 0.5 ) { x = Math.floor(x); } else if ( x > 0.5 ) { x = Math.floor(x + 1); } else { if ( Math.floor(originalX + 1) % 2 == 0 ) { x = Math.floor(originalX + 1); } else { x = Math.floor(originalX); } } x /= Math.pow(10, precision); return x; } |

The functions Math.floor() (floor and ceiling), Math.pow() (exponentiation), and the modulus operator, are usually already available for most modern languages, under the same names, and don’t really have a need to be re-implemented compared to the need to re-implement rounding. Implementing your own functions for these is usually relatively trivial, however.

There you go! Arbitrary precision rounding in any programming language and, thrown in for good measure, how to implement a different rounding method to boot!