Java 如何将字符串的值四舍五入到小数点后两位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20275401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to round a value of a String to 2 decimal places
提问by Alex
I have a String which is taken from a JSON file. I need to convert it to double or int and then round it to 2 decimal places and if its an int, round to 1 digit
我有一个取自 JSON 文件的字符串。我需要将它转换为 double 或 int,然后将其四舍五入到 2 个小数位,如果它是一个 int,则四舍五入到 1 位
for example: if it is 76424443 it should be rounded to 76.4 or if it is 7.122345936298 should be rounded to 7.12
例如:如果是 76424443 应该四舍五入到 76.4 或者如果是 7.122345936298 应该四舍五入到 7.12
This is what I have done so far.
这是我迄今为止所做的。
int value = Integer.parseInt(value1);
value1 = String.valueOf(Math.round(value));
I also do not know if the value is double or int, should be something that works with both.
我也不知道该值是 double 还是 int,应该对两者都适用。
采纳答案by gahfy
Try this code :
试试这个代码:
Double value = Double.parseDouble(value1);
String value1 = "0";
if(value != null){
if(value == (double) Math.round(value)){
if(value/1000000000 > 1.0){
value1 = String.format("%.1f G", value/1000000000);
}
else if(value/1000000 > 1.0){
value1 = String.format("%.1f M", value/1000000);
}
else if(value/1000 > 1.0){
value1 = String.format("%.1f K", value/1000);
}
else{
value1 = String.format("%.1f", value);
}
}
else{
value1 = String.format("%.2f", value);
}
}
回答by Little Child
Consider using a BigDecimal. It will let you round your values to the precision you like. Have a look at this answer: Set specific precision of a BigDecimal
考虑使用 BigDecimal。它将让您将值四舍五入到您喜欢的精度。看看这个答案:Set specific precision of a BigDecimal
If you cast a decimal value to integer then you will lose the decimal part. If that is the case then why bother rounding at all ?
如果您将十进制值转换为整数,那么您将丢失小数部分。如果是这样,那为什么还要四舍五入呢?