我有一个从外部方法调用中提取的 double 值。当 0.6 值出现时,我希望将其更改为 0.60,但我不想在字符串末尾添加“0”,否则它会使我的 0.65 值变为 0.650。
我之前遇到过一个问题,它将 1.95 显示为 195000001,但我已经解决了这个问题。
double convPrice = callMethod.totalPriceMethod(); //Calls value from external method and adds to local variable.
totalPrice = Double.toString(convPrice); //local variable is converted to String
totalPrice = String.format("£%.2f", totalPrice ); //Formatting is applied to String
totalPriceLabel.setText(totalPrice); //String is added to JLabel.
任何帮助将不胜感激。
最佳答案
只需对 float 使用 String.format 格式说明符:
String.format("%.2f", yourNumber)
教程:Formatting tutorial .
或者使用 DecimalFormat 对象。
<小时/>例如,
String s = String.format("%.2f", 0.2);
System.out.println(s);
<小时/>
不要将 double 转换为字符串预格式化,因为这就是格式化的目的。你正在这样做
double convPrice = callMethod.totalPriceMethod();
totalPrice = Double.toString(convPrice);
totalPrice = String.format("£%.2f", totalPrice );
totalPriceLabel.setText(totalPrice);
当你想做这样的事情时:
double convPrice = callMethod.totalPriceMethod();
// totalPrice = Double.toString(convPrice); // ???????
totalPrice = String.format("£%.2f", convPrice);
totalPriceLabel.setText(totalPrice);
由于您要转换为货币,因此使用 NumberFormatcurrencyInstance 可能会更好。
例如,
NumberFormat currencyInstance = NumberFormat.getCurrencyInstance(Locale.UK);
double convPrice = callMethod.totalPriceMethod();
totalPriceLabel.setText(currencyInstance.format(convPrice));
关于java - 将尾随 0 添加到我的 0.1、0.2 值,但不添加到我的 0.25 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28916530/