Java BigDecimal class small processing

BigDecimal is a commonly used class for handling high-precision floating-point arithmetic

When it is necessary to print out the floating-point value stored in BigDecimal, especially when it is displayed on the page, it is possible to encounter unexpected problems of scientific and technical representation.

Generally , the printing of floating-point numbers can be completed directly by using the BigDecimal.toString() method .

Such as:

    System.out.println( new BigDecimal("10000000000").toString());

However, the string output by the toString() method is not guaranteed not to be scientific notation.

However, in daily use, the output of the toString() method is a normal number string instead of scientific notation.

Just write it like this:

    System.out.println( new BigDecimal("100.000").toString());

The output of the program is then: 100.000

If we want to remove the extra 0 at the end, then we should write:

    System.out.println( new BigDecimal("100.000").stripTrailingZeros().toString());

Among them, the stripTrailingZeros() function is used to remove the excess 0 at the end, but the output of the program is: 1E+2

is scientific notation, which may not be what we want.

The solution is simple, if you want to avoid outputting strings in scientific notation, we use the toPlainString() function instead of toString() . Such as:

    System.out.println( new BigDecimal("100.000").stripTrailingZeros().toPlainString());

At this point the output of the program is 100

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325884890&siteId=291194637