java - 将尾随 0 添加到我的 0.1、0.2 值,但不添加到我的 0.25 值

标签 java formatting

我有一个从外部方法调用中提取的 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/

相关文章:

java - NoSuchAlgorithmException : Error constructing implementation while connecting to SSL website through JAVA 8

java - 如何使用 JUnit 测试异步进程

java - MM/dd/yyyy 格式的 xmlgregoriancalendar

flutter - 如何在 dart 中将时间戳字符串从 24 小时格式转换为 12 小时格式?

C# 格式化货币

javascript - 你将如何在 JavaScript/HTML 中实现自动大写

java - 使用方法时日历给出错误的年份

java - 如何使用在方法自身中调用方法的变量?

java - 添加/保存的数据无效 (addPerson)

C编程制作乘法表(1-12)