java小數(shù)位的例子
更新時間:2013年11月11日 14:18:03 作者:
在java中要保留數(shù)字小數(shù)位我們有常用的四種方法,分別為:四舍五入,DecimalFormat,format,String .format與struts標簽操作實現(xiàn),下面給出例子
方式一:
四舍五入
double f = 111231.5585;
四舍五入 保留兩位小數(shù),可以用String的format函數(shù),
方法如下:
復制代碼 代碼如下:
System.out.println(String.format("%.2f", x1));
System.out.println(String.format("%.2f", x2));
DecimalFormat轉換最簡便
復制代碼 代碼如下:
public void m2() {
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f));
}
例:new java.text.DecimalFormat(”#.00″).format(3.1415926)
#.00 表示兩位小數(shù) #.0000四位小數(shù) 以此類推…
方式三:
復制代碼 代碼如下:
double d = 3.1415926;
String result = String .format(”%.2f”);
%.2f %. 表示 小數(shù)點前任意位數(shù) 2 表示兩位小數(shù) 格式后的結果為f 表示浮點型。
方式四:
此外如果使用struts標簽做輸出的話,有個format屬性,設置為format="0.00"就是保留兩位小數(shù)
例如
復制代碼 代碼如下:
<bean:write name="entity" property="dkhAFSumPl" format="0.00" />
JAVA中保留N位小數(shù)的方法,例子 .
復制代碼 代碼如下:
import java.text.DecimalFormat;
public class numberFarmat {
public static void main(String[] args) {
double sd = 23.2558896635;
//第一種方法 10000.0這個小數(shù)點后只表示保留小數(shù),和位數(shù)沒關系。
double d1 = (double) (Math.round(sd*10000)/10000.0000000000);
double d2 = (double) (Math.round(sd*10000)/10000.0);
System.out.println("4位小數(shù)測試:"+d1);
System.out.println("4位小數(shù)測試:"+d2);
//第二種方法
DecimalFormat df2 = new DecimalFormat("###.00");
DecimalFormat df3 = new DecimalFormat("##.000");
System.out.println("3位小數(shù):"+df3.format(sd));
System.out.println("2位小數(shù):"+df2.format(sd));
}
}
運行結果如下:
4位小數(shù)測試:23.2559
4位小數(shù)測試:23.2559
3位小數(shù):23.256
2位小數(shù):23.26
相關文章
Springboot集成RabbitMQ死信隊列的實現(xiàn)
在大多數(shù)的MQ中間件中,都有死信隊列的概念。本文主要介紹了Springboot集成RabbitMQ死信隊列的實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
SpringSecurity JWT基于令牌的無狀態(tài)認證實現(xiàn)
Spring Security中實現(xiàn)基于JWT的無狀態(tài)認證是一種常見的做法,本文就來介紹一下SpringSecurity JWT基于令牌的無狀態(tài)認證實現(xiàn),感興趣的可以了解一下2025-04-04
Springboot+WebSocket實現(xiàn)在線聊天功能
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡協(xié)議。這篇文章主要為大家介紹了如何利用Springboot和WebSocket實現(xiàn)在線聊天功能,感興趣的小伙伴可以了解一下2023-02-02
Maven項目如何在pom文件中引入lib下的第三方jar包并打包進去
在使用Maven進行項目開發(fā)時,引入第三方私有的Jar包可能會遇到問題,一種常見的解決方案是將Jar包添加到項目的lib目錄,并通過IDE進行配置,但這需要每個開發(fā)者單獨操作,效率低下,更好的方法是通過Maven的pom.xml文件管理這些Jar包
2024-09-09 
