public class MathTester { public MathTester() { double d = 1.4; double multiplier1 = 0.000001; double multiplier2 = 0.0001; d = d * multiplier1; d = d / multiplier2; System.out.println(d);
int decimalPlace = 2;
BigDecimal bigDecimal = new BigDecimal(d); bigDecimal = bigDecimal.setScale(decimalPlace ,BigDecimal.ROUND_HALF_UP); d = bigDecimal.doubleValue(); System.out.println(d);
}
public static void main(String[] args) { new MathTester(); } }
I'm just able to use 1.4 so I guess I need to use:
BigDecimal bigDecimal = new BigDecimal(d); bigDecimal = bigDecimal.setScale(decimalPlace ,BigDecimal.ROUND_HALF_UP); d = bigDecimal.doubleValue(); Best regards Fredrik
When i hit this issue i usually get around it in a "noobish" kind of way, but it still works. Ex: If i get the double 14.50006 and only want 2 digits ill just multiply with 100 and parse to integer and then back to double:
double d = 14.50006*100; int i = Integer.parseInt(d); d = i/100;
double d = 14.50006*100; int i = (int)d; d = i/100.0;
because what posted does really not work.
That is an OK solution if you want to round well within the precision of floating point.
It does not really solve the precision problem.
And as a side note:
x = ((int)(x * 100))/100.0;
always round down - there is a relative good probability that
x = ((int)(x * 100 + 0.5))/100.0;
which rounds to nearest is better
Synes godt om
Ny brugerNybegynder
Din løsning...
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.