Four ways to keep two decimal places in Java

  • 2021-06-28 12:48:35
  • OfStack

When writing a program, you may sometimes need to set the number of decimal places, so how many ways to keep the number of decimal places in java? #63;This paper gives four methods with two decimal numbers as an example.


package CodeJava_Leet;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
 * Created by Yechengpeng on 2016-08-14.
 */
public class Test {
  public static void main(String[] args) {
    double d = 756.2345566;
    // Method 1 : The easiest way to call DecimalFormat class 
    DecimalFormat df = new DecimalFormat(".00");
    System.out.println(df.format(d));
    // Method 2 : directly through String Class format Function implementation 
    System.out.println(String.format("%.2f", d));
    // Method 3 : Passed BigDecimal Class implementation 
    BigDecimal bg = new BigDecimal(d);
    double d3 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    System.out.println(d3);
    // Method 4 : Passed NumberFormat Class implementation 
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);
    System.out.println(nf.format(d));
  }
}

The output is:

D:\Java\jdk1.8.0\...
756.23
756.23
756.23
756.23
Process finished with exit code 0

summary


Related articles: