I am translating .NET code to Java and ran into precision not matching issue.
.NET code:
private decimal roundToPrecision(decimal number, decimal roundPrecision)
{
if (roundPrecision == 0)
return number;
decimal numberDecimalMultiplier = Math.Round(number / roundPrecision, MidpointRounding.AwayFromZero);
return numberDecimalMultiplier * roundPrecision;
}
Calling roundToPrecision(8.7250, 0.05);
function in the code above gives me 8.75
which is expected.
The conversion/translation of the function to Java is as follows. I din't find exact
Math.Round
option.
Java code:
public double roundToPrecision(double number, double roundPrecision) {
if (roundPrecision == 0)
return number;
int len = Double.toString(roundPrecision).split("\\.")[1].length();
double divisor = 0d;
switch (len) {
case 1:
divisor = 10d;
break;
case 2:
divisor = 100d;
break;
case 3:
divisor = 1000d;
break;
case 4:
divisor = 10000d;
break;
}
double numberDecimalMultiplier = Math.round(number / roundPrecision);
double res = numberDecimalMultiplier * roundPrecision;
return Math.round(res * divisor) / divisor;
}
Calling roundToPrecision(8.7250, 0.05);
in the Java code gives me 8.7
and this is not correct.
I even tried modifying code with BigDecimal
as follows in Java using the reference here C# Double Rounding but have no luck.
public double roundToPrecision(double number, double roundPrecision) {
if (roundPrecision == 0)
return number;
int len = Double.toString(roundPrecision).split("\\.")[1].length();
double divisor = 0d;
switch (len) {
case 1:
divisor = 10d;
break;
case 2:
divisor = 100d;
break;
case 3:
divisor = 1000d;
break;
case 4:
divisor = 10000d;
break;
}
BigDecimal b = new BigDecimal(number / roundPrecision);
b = b.setScale(len,BigDecimal.ROUND_UP);
double numberDecimalMultiplier = Math.round(b.doubleValue());
double res = numberDecimalMultiplier * roundPrecision;
return Math.round(res * divisor) / divisor;
}
Please guide me for what I need to do to fix this.
Here are couple of scenarios to try out.
- number =
10.05
; precision =.1
; expected =10.1
; - number =
10.12
; precision =.01
; expected =10.12
; - number =
8.7250
; precision =0.05
; expected =8.75
; - number =
10.999
; precision =2
; expected =10
; - number =
6.174999999999999
; precision =0.05
; expected =6.20
;
Note: I have over 60 thousand numbers and precision can vary from 1 decimal to 4 decimal places. The output of .NET should match exactly to Java.