0

I am trying to print my number 12386876764.34 and I want my output as the same. I tried the following to print my number, but could not find a way to print the same. Please provide a solution for this.

public static void main(String[] args) {
    System.out.println((12386876764.34*100)/100);
    System.out.println(Math.round(12386876764.34*100)/100);
    System.out.println((new BigDecimal((12386876764.34*100)/100)).toPlainString());
    System.out.println((new BigDecimal(Math.round(12386876764.34*100)/100)).toPlainString());
}

Output: 1.238687676434E10 12386876764 12386876764.340000152587890625 12386876764

Ezazul
  • 11
  • 1
  • 4
  • `System.out.println(String.format("%.2f", 12386876764.34));` – Jacob G. Sep 17 '17 at 02:43
  • Use the string constructor for `BigDecimal`. Your numeric literal is losing precision going through the `double` constructor. `new java.math.BigDecimal("12386876764.34")` – Chris Martin Sep 17 '17 at 02:46
  • 1
    This is *not* the same as the question it was closed as being a duplicate of, because that one is about formatting floating-point numbers - this question calls for avoiding the use of floating-point numbers altogether. – Chris Martin Sep 17 '17 at 02:48
  • Clarify your question title next time so it doesn't get mistaken for duplicate. Just a tip. – SassyRegards201 Sep 17 '17 at 05:03
  • This *is* the same question. A `double` has more than enough precision to represent the value. `System.out.printf("%.2f%n", 12386876764.34D);` The decision to use `BigDecimal` is based on the application. For engineering and computation of physical models, use `float` or `double`. For finance, use `BigDecimal`. – erickson Sep 17 '17 at 05:21

0 Answers0