Packagecom.clzhang.sample;ImportJava.math.BigDecimal;ImportJava.math.RoundingMode;ImportJava.text.DecimalFormat;ImportJava.text.NumberFormat; Public classDoubletest {/*** Keep Two decimal places, rounding up an old-fashioned way *@paramd *@return */ Public Static DoubleFormatDouble1 (Doubled) {return(Double) Math.Round (d*100)/100; } /*** The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and Format conversion. * @paramd *@return */ Public Static DoubleFormatDouble2 (Doubled) {//old methods that are no longer recommended for use//BigDecimal bg = new BigDecimal (d). Setscale (2, bigdecimal.round_half_up); //New method, if rounding is not required, you can use Roundingmode.downBigDecimal BG =NewBigDecimal (d). Setscale (2, Roundingmode.up); returnBg.doublevalue (); } /*** NumberFormat is the abstract base class for all number formats. * This class provides the interface for formatting and parsing numbers. * @paramd *@return */ Public StaticString FormatDouble3 (Doubled) {NumberFormat NF=numberformat.getnumberinstance (); //keep two decimal placesNf.setmaximumfractiondigits (2); //If rounding is not required, you can use the Roundingmode.downNf.setroundingmode (roundingmode.up); returnNf.format (d); } /*** This method is quite simple. * DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. * @paramd *@return */ Public StaticString FormatDouble4 (Doubled) {DecimalFormat df=NewDecimalFormat ("#.00"); returnDf.format (d); } /*** This method is quite handy if you are only using formatted values in the program and then outputting them. * Should be used in this way: System.out.println (String.Format ("%.2f", d)); * @paramd *@return */ Public StaticString FormatDouble5 (Doubled) {returnString.Format ("%.2f", D); } Public Static voidMain (string[] args) {DoubleD = 12345.67890; System.out.println (FormatDouble1 (d)); System.out.println (FormatDouble2 (d)); System.out.println (FormatDouble3 (d)); System.out.println (FormatDouble4 (d)); System.out.println (FormatDouble5 (d)); }}
Java double type retains two decimal places and rounding