Java outputs multiple decimal places (three methods)


Method 1: the method of String class

The most common way:
image.png

double a=3.141111;
System.out.println(String.format("%.1f",a));//保留一位小数
System.out.println(String.format("%.2f",a));//保留两位小数
System.out.println(String.format("%.3f",a));//保留三位小数
System.out.print(String.format("%.4f",a));//用print可以取消换行

Method 2: printf formatted output

Similar to the C language, Java can also output through printf:
image.png

double a=3.141111;
System.out.printf("%.1f",a);//保留一位小数
System.out.printf("%.2f",a);//保留两位小数
System.out.printf("%.3f",a);//保留三位小数
System.out.printf("%.4f\n",a);//加\n可以换行

Method 3: The way of the DecimalFormat class

DecimalFormat is a specific subclass of NumberFormat, used to format decimal numbers, mainly by 0 and # two placeholder symbols.
#Indicates the required number of digits if possible.
0 means that if the number of digits is insufficient, it will be filled with 0.
image.png

//class前=导入:
import java.text.DecimalFormat;
//#的使用:
DecimalFormat a = new DecimalFormat("#.#");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("#.#");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("##.##");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("###.###");
System.out.println(a.format(12.34)); //打印12.34

It can be seen that # doesn't seem to have any effect, it prints whatever should be printed, but it is not like this, it is mostly used with 0, which plays a big role.

//0的使用:
DecimalFormat a = new DecimalFormat("0.0");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("00.00");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("000.000");
System.out.println(a.format(12.34)); //打印012.340
//#和0的使用
DecimalFormat a = new DecimalFormat("#.#");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("#.#");
System.out.println(a.format(12.34)); //打印12.34

DecimalFormat a = new DecimalFormat("##.##");
System.out.println(a.format(12.34)); //打印12.34

Example (full code):

import java.text.DecimalFormat;
public class Test {
    
    
    public static void main(String[] args) {
    
    
        DecimalFormat a = new DecimalFormat("#.00");
        System.out.println(a.format(12.34567)); //四舍五入输出12.35
    }
}

Guess you like

Origin blog.csdn.net/weixin_74837727/article/details/130090751