作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这个代码:
public double theInterest(){
return (accountBalance*i) +accountBalance;
我的问题是,有没有一种方法可以将 DecimalFormat 应用于方程式的结果,以便它最多显示 2 位小数?
非常感谢任何帮助。
最佳答案
您的问题已发布,无法回答,因为该方法返回一个 double 值,而 DecimalFormat 只能返回一个字符串。尝试返回格式化的 double 是没有意义的。我不建议你改变方法,但考虑创建一个单独的方法,比如 getInterestString()
,它获取 theInterest()
的结果,并使用你的格式DecimalFormatter 然后返回这个格式化的字符串。
即,
public String getInterestString() {
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
return moneyFormat.format(theInterest();
}
或者更一般地说,
private NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
public String currencyFormat(double numberValue) {
moneyFormat.format(numberValue);
}
编辑:正如 svc 所说,您应该努力避免使用 float 进行货币计算,因为不准确很重要。最好使用 BigDecimal。
关于java - 如何对方法的结果施加 decimalFormat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16068876/
我是一名优秀的程序员,十分优秀!