我有一个BigDecimal数字,我只考虑它的2个小数位,所以我使用以下方法截断了它:
bd = bd.setScale(2, BigDecimal.ROUND_DOWN)
现在,我想将其打印为String,但是如果它为0,则删除小数部分,例如:
1.00-> 1
1.50-> 1.5
1.99-> 1.99
我尝试使用Formatter,formatter.format,但我总是得到2个十进制数字。
我怎样才能做到这一点?也许正在处理bd.toPlainString()中的字符串?
Answers:
我用DecimalFormat格式化BigDecimal而不是格式化String,似乎没有问题。
代码是这样的:
bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);
String result = df.format(bd);
df.setMinimumFractionDigits(2)没有setScale和setGrouping和setMaxFrac的情况下可以正常工作。
NumberFormat numberFormat = NumberFormat.getPercentInstance();再numberFormat.setMinimumFractionDigits(2);然后String percent = numberFormat.format(yourBigDecimal);
BigDecimal.ROUND_DOWN不推荐使用Java 9及更高版本。使用RoundingMode.DOWN代替。
new DecimalFormat("#0.##").format(bd)
new DecimalFormat("0.00"),如果我想,以确保两位小数始终显示,例如,1000.5会显示1000.50。
import java.math.BigDecimal; import java.text.*; public class LocalizeExample { public static void main(String[] args) { BigDecimal bd = new BigDecimal("123.10"); DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(Locale.GERMAN); decimalFormat.applyPattern("#0.00"); String result = decimalFormat.format(bd); System.out.println(result); } }
以下代码可能会对您有所帮助。
protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
numberFormat.setGroupingUsed(true);
numberFormat.setMaximumFractionDigits(2);
numberFormat.setMinimumFractionDigits(2);
return numberFormat.format(input);
}