我想使用3位有效數字轉換字符串值。如何使用3位有效數字寫入字符串而不捨入
我使用這個代碼:
String s = "0,92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("#,###");
String end = formatter.format(f);
結果是端= 0.000。但是我想要結束= 0,920。我怎樣才能做到這一點?
我想使用3位有效數字轉換字符串值。如何使用3位有效數字寫入字符串而不捨入
我使用這個代碼:
String s = "0,92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("#,###");
String end = formatter.format(f);
結果是端= 0.000。但是我想要結束= 0,920。我怎樣才能做到這一點?
如果在您當前的語言環境中,小數點分隔符是點,那麼您將得到0.920。如果你想獲得獨立於你的結果當前區域有作爲小數點分隔符逗號和千個分隔符一個點,你可以實現它例如像這樣
String s = "0.92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("0.000", DecimalFormatSymbols.getInstance(Locale.GERMANY));
String end = formatter.format(f);
System.out.println("end = " + end);
這將打印
end = 0,920
非常感謝。有用 !! – eren
這個工作對我來說:
String s = "0.92";
float f = Float.parseFloat(s);
DecimalFormat formatter = new DecimalFormat("0.000");
String end = formatter.format(f);
System.out.println(end);
請注意 ''在字符串中和DecimalFormat中的模式。
','這裏意味着1000標記,即。一百萬1,000,000.00。
你真的意思是拿'',而不是'.'? – Baby
對不起。我編輯了這個問題。 – eren
由於Jonjongot暗示,你應該將原始值(「0,92」)中的逗號更改爲句點 - 只有parseFloat將能夠將該字符串轉換爲浮點並讓格式化工作... –