Bigdecimal removes the extra 0 at the end, stripTrailingZeros().toPlainString()

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

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

Generally, the BigDecimal.toString() method can be used directly to print floating-point numbers.

Such as:

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

However, the string output by the toString() method does not guarantee that it is not scientific notation.

However, in daily use, the output of the toString() method is an ordinary string of numbers instead of scientific notation.

Write directly like this:

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

The output of the program is: 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 extra 0 at the end, but the output of the program at this time is: 1E+2

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

The solution is very simple. If we want to avoid outputting the scientific notation string, we have to use toPlainString() instead of toString(). Such as:

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

At this time, the output of the program is 100
original link: https://blog.csdn.net/xingxiupaioxue/java/article/details/78088337

Guess you like

Origin blog.csdn.net/shu_quan/article/details/105580061