我像这样使用 Java NumberFormat:
NumberFormat format = NumberFormat.getNumberInstance(locale);
format.maximumFractionDigits = 2;
String number = format.format(price);
当 double 值为:19.95 时,我得到正确本地化为德语格式的 19,95。 当 double 值为:19.5 时,我得到 19,5,这是一个错误的格式。
如果价格是 19.50,我需要恰好获得两位数字,即 19,50。 如果价格是 19.00,我需要得到零数字,即 19。
我该怎么做?
最佳答案
这对我有用:
NumberFormat format = NumberFormat.getNumberInstance(Locale.GERMAN);
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
double price = <your price>;
int priceAsInt = (int)price;
if(((double)priceAsInt) == price) {
String number = String.valueOf(priceAsInt);
System.out.println(number);
} else {
String number = format.format(price);
System.out.println(number);
}
关于java - NumberFormat 允许零或两位数字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32565265/