Java輸出多位小數(shù)的三種方法(附代碼)
方法一:String類的方式
最常用的方式:

double a=3.141111;
System.out.println(String.format("%.1f",a));//保留一位小數(shù)
System.out.println(String.format("%.2f",a));//保留兩位小數(shù)
System.out.println(String.format("%.3f",a));//保留三位小數(shù)
System.out.print(String.format("%.4f",a));//用print可以取消換行方法二:printf格式化輸出
與C語言相似,Java中也可以通過printf輸出:

double a=3.141111;
System.out.printf("%.1f",a);//保留一位小數(shù)
System.out.printf("%.2f",a);//保留兩位小數(shù)
System.out.printf("%.3f",a);//保留三位小數(shù)
System.out.printf("%.4f\n",a);//加\n可以換行方法三:DecimalFormat類的方式
DecimalFormat 是 NumberFormat 的一個具體子類,用于格式化十進制數(shù)字,主要靠0和#兩個占位符號。#表示如果盡可能占需占的位數(shù)。0表示如果位數(shù)不足則用0補足。

//class前=導(dǎo)入: 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
可以看出,#好像并沒有什么作用,該打印什么就打印什么,但并不是這樣的,它是與大多與0一起使用,起著很大的作用。
//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
舉例(完整代碼):
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
}
}總結(jié)
到此這篇關(guān)于Java輸出多位小數(shù)的三種方法的文章就介紹到這了,更多相關(guān)Java輸出多位小數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
通過IEAD+Maven快速搭建SSM項目的過程(Spring + Spring MVC + Mybatis)
這篇文章主要介紹了通過IEAD+Maven快速搭建SSM項目的過程(Spring + Spring MVC + Mybatis),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01
Springboot集成Minio實現(xiàn)文件上傳基本步驟
這篇文章主要介紹了Springboot集成Minio實現(xiàn)文件上傳基本步驟,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2025-06-06
Eclipse開發(fā)JavaWeb項目配置Tomcat的方法步驟
本文主要介紹了Eclipse開發(fā)JavaWeb項目配置Tomcat的方法步驟,首先介紹eclipse開發(fā)JavaWeb項目需要配置的相關(guān)環(huán)境,使用tomcat軟件在本地搭建服務(wù)器,然后再在eclipse環(huán)境下配置tomcat,感興趣的可以了解一下2021-08-08
解決Idea報錯There is not enough memory
在使用Idea開發(fā)過程中,可能會遇到因內(nèi)存不足導(dǎo)致的閃退問題,出現(xiàn)"There is not enough memory to perform the requested operation"錯誤時,可以通過調(diào)整Idea的虛擬機選項來解決,方法是在Idea的Help菜單中選擇Edit Custom VM Options2024-11-11

