Tuesday, January 13, 2009

Rounding in different environments

Again, take care when working in multiple environments:

In Excel you get:

ROUND(4,4245;2) -> 4.25
(depending on a preference setting)

in Oracle you get:

select round(4.245, 2) from dual -> 4.25

in VB6 one gets:

Round(4.245, 2) -> 4.24

But you can use:


Function RoundHalfUp(number As Double, scale As Integer) As Double
RoundHalfUp = Int(number * 10 ^ scale+ 0.5) / 10 ^ scale
End Function


In Java you can directly use BigDecimal or the following utility for doubles:


/**
* Rounds the given value half up.
*
* @param value the value to round
* @param scale the scale to use for rounding
* @return a new rounded BigInteger instance
*/
public double roundHalfUp(final double value, final int scale) {
return new BigDecimal(Double.toString(value)).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}


In JavaScript the Math.round() has no scale, so again we use simple math:


function roundHalfUp(x, n)
{
var a = Math.pow(10, n);
return (Math.round(x * a, 0) / a);
}

No comments:

Post a Comment