[英]How to print float value with two decimal and without decimal in java
這是我的代碼
float realvalue = 7.5
worthValue = "£" + String.format(String.valueOf(value - (float) .50));
我想顯示這樣的值,如果 realvalue 為 7.5,那么它應該顯示 valueValue 7,而當 realvalue 為 8 時,它應該顯示 valueValue 7.50 請幫助我在這個如何顯示有和沒有浮點值的小數
試試這樣:
String worthValue;
float realValue = 8f;
if (realValue % 1 == 0f) {
worthValue = String.format("£ %.2f", realValue - 0.5);
} else {
worthValue = String.format("£ %d", (int) (realValue - 0.5));
}
希望這對你有用!
您可以使用 DecimalFormatter 像這樣格式化您的值。
DecimalFormat paymentFormatter = new DecimalFormat("#,###,###.##");
paymentFormatter.format(input);
嘗試這個。
static String format(float f) {
String r = String.format("%.2f", f);
if (r.endsWith(".00"))
return r.substring(0, r.length() - 3);
return r;
}
和
float realValue1 = 7.5f;
System.out.println("£" + format(realValue1 - 0.5f));
float realValue2 = 8.0f;
System.out.println("£" + format(realValue2 - 0.5f));
結果:
£7
£7.50
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.