After removal of excess BigDecimal types variable decimal zero

       Business Background : mysql field in Type B of Table A is decimal type, number of decimal places is three, the value of a piece of data is 3000000, check out the result in Java 3000000.000, so does not look good in the page display The user would like to see is 3,000,000. 
      Solution : Use stripTrailingZeros () toPlainString () to resolve. The following example illustrates how to remove the extra zeros after a decimal point BigDecimal type variable: 
= TestData the BigDecimal new new the BigDecimal ( "3,000,000.000" ); 
System.out.println ( "converted directly into an output string:" + testData.toString ()); 
System.out.println ( "unnecessary to remove trailing zero revolutions and converting after a string output: "+ . testData.stripTrailingZeros () toString ()); 
System.out.println ( " display only the value: "+ testData.stripTrailingZeros (). toPlainString ()); 
System.out.println ( " engineering notation output: "+ testData.stripTrailingZeros () toEngineeringString ( ));.

        Test Results: 

After the output is directly converted into a string: 3000000.00 
remove unwanted trailing zero revolutions and converted into an output string: 3E +6 
only show values: 3000000 
output counting Engineering: 3E +6  
      However, if the non-zero digital scene after the decimal point to 3000000.700 3000000.000 like, the stripTrailingZeros (). ToString () does not output scientific notation.
     toString (), toPlainString (), toEngineeringString () These three methods are used to convert a string BigDecimal, except that toString () it is possible to use the scientific notation, toPlainString () values ​​show only, not use scientific notation, toEngineeringString () engineering notation, and LCyT similar, but requires a power of 10 must be a multiple of 3.
toPlainString
toEngineeringString
1000
1 * 10^3
1 * 10^3
10000
1 * 10^4
10 * 10^3
100000
1 * 10^5
100 * 10^3
1000000
1 * 10^6
1 * 10^6
However, the following method can not be used stripTrailingZeros () remove unwanted end zero, only manual conversion.
public  static  void main (String [] args) { 
    the BigDecimal ratio = new new the BigDecimal ( "0.00" ); 
    System.out.println (ratio.stripTrailingZeros () toPlainString ().); 
    // own judgment, when judged equal, using comparTo (), equals () do not fly 
    IF (0 == BigDecimal.ZERO.compareTo (ratio)) { 
        System.out.println ( "0" ); 
     } 
    IF (! BigDecimal.ZERO.equals (ratio)) { 
         System.out.println ( "actually not equal" ); 
    } 
} 
       总结:BigDecimal是处理高精度的浮点数运算的常用的一个类,当需要将BigDecimal中保存的浮点数值打印出来,特别是在页面上显示的时候,就有可能遇到意料之外的科学技术法表示的问题。 stripTrailingZeros()可以去除小数点后多余的0,用科学记数法表示,再结合toPlainString()即可输出数值。
 
 
 
 
 
 
 
 
 
 

Guess you like

Origin www.cnblogs.com/east7/p/11708141.html