1

What I would like to do is a method to round float number to N decimal places (N will be given in stdin), do some math operation with it and then print the result. I found this:

   public BigDecimal round(float number, int decimal){
   BigDecimal obj = new BigDecimal(number).setScale(decimal, BigDecimal.ROUND_HALF_UP);
   return obj;

Which works pretty well, but not when number N (int decimal in this method) is high. For example: x = -10, y = -11.8814, N = 8 and it prints this:

-10.00000000 + -11.88140011 = -21.88140106

And this is what I would want:

-10.00000000 + -11.88140000 = -21.88140000

Thanks everybody for suggestions :)

H. Mares
  • 33
  • 1
  • 6

4 Answers4

2

I think the easiest thing to do is multiply your numbers by 10^N and use round() to turn them into integers. Run your math and then divide them back down

    public static void main(String[] args) {
        double a = -10.0;
        double b = -11.88140011;
        int n = 4;
        long total = round(a, n) + round(b, n);

        System.out.println(String.format("%.8f%n", total * Math.pow(10, -1*n)));
    }

    static Long round(double number, int decimal) {
        return Math.round(number * Math.pow(10, decimal));
    }
mike
  • 565
  • 1
  • 3
  • 18
1

There is no float representation of 11.88140000 with all 8 decimal places intact, so at the moment you pass that number to your method regardless of the implementation it has no chance to return the wanted result, see article for float on Wikipedia:

... the total precision is 24 bits (equivalent to log10(224) ≈ 7.225 decimal digits)

And that precision is including all digits, not only those after the decimal separator.

Markus Benko
  • 1,507
  • 8
  • 8
0

Your question already has an answer, but to understand the problem float vs. decimal better, there is another post about the problem explaining it a bit more in depth (same for every programming language):

Just for completeness: 0.3 would be exactly stored as it is in a BigDecimal. In float (due to it's binary nature), it would be stored as 0.30000001192092896. You instantiate your BigDecimal using a float and directly step into this problem.

Community
  • 1
  • 1
themole
  • 363
  • 3
  • 12
0

So, here is the answer. I didn't use function round I only printed the numbers with results:

System.out.printf("%." + n + "f + %." + n + "f = %." + n + "f\n", a, b, a + b);

Which I tried before I posted this question, BUT I used float and haven't tried using double (with function nextDouble() for scanning). So, double was the answer.

Thanks for your suggestions! :))

H. Mares
  • 33
  • 1
  • 6