Use a DecimalFormatter:
double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));
Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.
Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).
Answer from Alex on Stack OverflowUse a DecimalFormatter:
double number = 0.9999999999999;
DecimalFormat numberFormat = new DecimalFormat("#.00");
System.out.println(numberFormat.format(number));
Will give you "0.99". You can add or subtract 0 on the right side to get more or less decimals.
Or use '#' on the right to make the additional digits optional, as in with #.## (0.30) would drop the trailing 0 to become (0.3).
If you want to print/write double value at console then use System.out.printf() or System.out.format() methods.
System.out.printf("\n$%10.2f",shippingCost);
System.out.printf("%n$%.2f",shippingCost);
Videos
Hi, how do i truncate the result of a calculation to 2 decimals; for instance if the result is 19.899 or 19.892 i want the system to print 19.89 regardless. Thanks and merry christmas:))
That code will die a horrible death if the division has a non-terminating decimal expansion. See javadoc of divide(BigDecimal divisor):
if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an
ArithmeticExceptionis thrown.
Example:
BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
one.divide(x); // throws java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
Use one of the other overloads of divide(), e.g. divide(BigDecimal divisor, int scale, RoundingMode roundingMode):
BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
BigDecimal quotient = one.divide(x, 5, RoundingMode.HALF_UP);
System.out.println(quotient); // prints: 0.14286
BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
BigDecimal quotient = one.divide(x, 30, RoundingMode.HALF_UP);
System.out.println(quotient); // prints: 0.142857142857142857142857142857
To set the number of decimal places in a variable BigDecimal you can use the following sentences depend that you want achieve
value = value.setScale(2, RoundingMode.CEILING) to do 'cut' the part after 2 decimals
or
value = value.setScale(2, RoundingMode.HALF_UP) to do common round
See Rounding BigDecimal to *always* have two decimal places