java double保留兩位小數(shù)問題
更新時間:2025年03月08日 11:43:55 作者:早起的年輕人
在Java中,可以使用DecimalFormat或String.format來保留double類型數(shù)字的兩位小數(shù),這兩個方法都會進行四舍五入
java double保留兩位小數(shù)
在Java中,你可以使用 DecimalFormat
或 String.format
來保留 double 類型的數(shù)字兩位小數(shù)。
以下是兩個例子:
使用 DecimalFormat
import java.text.DecimalFormat; public class Main { public static void main(String[] args) { double number = 123.4567; DecimalFormat df = new DecimalFormat("#.00"); String result = df.format(number); System.out.println(result); // 輸出:123.46 } }
使用 String.format
public class Main { public static void main(String[] args) { double number = 123.4567; String result = String.format("%.2f", number); System.out.println(result); // 輸出:123.46 } }
這兩個例子都會將 double 類型的數(shù)字四舍五入到兩位小數(shù)。
注意 :
DecimalFormat
默認進行四舍五入- 而
String.format
的 “%.2f” 格式也意味著四舍五入到兩位小數(shù)
java double類型保留三位小數(shù)
/**工具類,直接調(diào)用,啥也不用改 * 提供精確的小數(shù)位四舍五入處理。 * @param v 需要四舍五入的數(shù)字 * @param scale 小數(shù)點后保留幾位 * @return 四舍五入后的結果 */ public static double round(double v,int scale) { if (scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /* main測試 */ public static void main(String[] args) { double d1 = 0.234566d; double d2 = 0.234566d; System.out.println("===== " + round(d1,3)); System.out.println("-----" + round(d2,1)); } /* 結果展示 */ ===== 0.235 ----- 0.2
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java警告:原發(fā)性版11需要目標發(fā)行版11的解決方法和步驟
這篇文章主要介紹了Java警告:原發(fā)性版11需要目標發(fā)行版11的解決方法和步驟,文中通過圖文介紹的非常詳細,對大家學習或者使用java具有一定的參考借鑒價值,需要的朋友可以參考下2025-04-04