我有一个从外部方法调用中提取的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.
任何帮助将不胜感激。
最佳答案
只需将String.format格式说明符用于浮点数即可:
String.format("%.2f", yourNumber)
教程位于:Formatting tutorial。
或使用DecimalFormat对象。
例如。,
String s = String.format("%.2f", 0.2);
System.out.println(s);
不要将double转换为String预格式化,因为这是格式化的目的。你在做这个
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);
由于您要转换为货币,因此使用NumberFormat currencyInstance可能更好。
例如。,
NumberFormat currencyInstance = NumberFormat.getCurrencyInstance(Locale.UK);
double convPrice = callMethod.totalPriceMethod();
totalPriceLabel.setText(currencyInstance.format(convPrice));
关于java - 在我的0.1、0.2值上加上尾随0,但不增加我的0.25值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28916530/