本文介紹了格式,Java 中雙精度和整數的 2 位小數和 0的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如果它有分數,我正在嘗試將雙精度格式化為精確的 2 位小數,否則使用 DecimalFormat 將其截斷
I am trying to format a double to exact 2 decimal places if it has fraction, and cut it off otherwise using DecimalFormat
所以,我想實現下一個結果:
So, I'd like to achieve next results:
100.123 -> 100.12
100.12 -> 100.12
100.1 -> 100.10
100 -> 100
變體 #1
DecimalFormat("#,##0.00")
100.1 -> 100.10
but
100 -> 100.00
變體 #2
DecimalFormat("#,##0.##")
100 -> 100
but
100.1 -> 100.1
有什么想法在我的情況下選擇什么模式?
Have any ideas what pattern to choose in my case?
推薦答案
我達到的唯一解決方案是使用這里提到的 if 語句:https://stackoverflow.com/a/39268176/6619441
The only solution i reached is to use if statement like was mentioned here: https://stackoverflow.com/a/39268176/6619441
public static boolean isInteger(BigDecimal bigDecimal) {
int intVal = bigDecimal.intValue();
return bigDecimal.compareTo(new BigDecimal(intVal)) == 0;
}
public static String myFormat(BigDecimal bigDecimal) {
String formatPattern = isInteger(bigDecimal) ? "#,##0" : "#,##0.00";
return new DecimalFormat(formatPattern).format(bigDecimal);
}
測試
myFormat(new BigDecimal("100")); // 100
myFormat(new BigDecimal("100.1")); // 100.10
如果有人知道更優雅的方式,請分享!
If someone knows more elegant way, please share it!
這篇關于格式,Java 中雙精度和整數的 2 位小數和 0的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!