英文:
Round percentage value to nearest number
问题
import java.math.RoundingMode;
import java.text.NumberFormat;
public class RoundingModeExample {
public static void main(String[] args) {
System.out.println(formatPercentage("0.0195") + "(expected 2.0%)");
System.out.println(formatPercentage("0.0401") + "(expected 4.0%)");
}
private static String formatPercentage(String number) {
String formattedValue = "";
NumberFormat numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMinimumFractionDigits(1);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
try {
formattedValue = numberFormat.format(Double.valueOf(number));
} catch (NumberFormatException e) {
formattedValue = number;
}
return formattedValue;
}
}
以上程序的输出:
1.9%(expected 2.0%)
4.0%(expected 4.0%)
英文:
I wanted to convert a number which is in string format to a percentage value with one decimal point. Below is my sample input and expected output.
Expected results:
"0.0195" => "2.0%"
"0.0401" => "4.0%"
I know this may be a simple question but I am not able to find the exact solution for this using java APIs, I tried all the rounding modes present under RoundingMode enum, but no rounding mode gives my expected result. Could you please help, I may be missing something.
import java.math.RoundingMode;
import java.text.NumberFormat;
public class RoundingModeExample {
public static void main(String[] args) {
System.out.println(formatPercentage("0.0195") + "(expected 2.0%)");
System.out.println(formatPercentage("0.0401") + "(expected 4.0%)");
}
private static String formatPercentage(String number) {
String formattedValue = "";
NumberFormat numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMinimumFractionDigits(1);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
try {
formattedValue = numberFormat.format(Double.valueOf(number));
} catch (NumberFormatException e) {
formattedValue = number;
}
return formattedValue;
}
}
Output of the above program:
1.9%(expected 2.0%)
4.0%(expected 4.0%)
答案1
得分: 6
问题在于 0.0195 存在一个问题,即没有一个double
精度的数字能够在数学上完全等于它。当你在程序源代码中编写 0.0195,或将字符串“0.0195”解析为双精度数时,得到的数字实际上会略微偏小。这就是为什么格式化程序会将其舍入为 1.9%。
你可以通过根本不使用double
数据类型来解决这个问题:
formattedValue = numberFormat.format(new BigDecimal(number));
英文:
The problem with 0.0195 is that there is no double
precision number that is exactly mathematically equal to it. When you write 0.0195 in program source code or parse the string "0.0195" into double, the number you get is actually a little bit less. That's why the formatter rounds it to 1.9%.
You can get around this by not using the double
data type at all:
formattedValue = numberFormat.format(new BigDecimal(number));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论