英文:
ceil or round off after decimal value in Java
问题
我有一个十进制值46.58,我想让它变成46.60,或者对于46.44,它将变成46.40。
尝试了几种方法,比如使用Math类的round函数和BigDecimal,但是在小数点后面的值没有被四舍五入。
BigDecimal bigDecimal = new BigDecimal(value);
bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
value = bigDecimal.doubleValue();
double value = Math.round(decimalValue);
英文:
I have a decimal value 46.58 i want it to be like 46.60 or for 46.44 it will be like 46.40.
Tried several ways like like Math class's round function and Bigdecimal but it is not roudning off after decimal values.
BigDecimal bigDecimal = new BigDecimal(value);
bigDecimal = bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
value = bigDecimal.doubleValue();
double value = Math.round(decimalValue);
答案1
得分: 3
你首先需要使用标准的"半上舍入" RoundingMode
将数值四舍五入到小数点后1位,然后再将小数点后的精度增加到2位:
BigDecimal bigDecimal = new BigDecimal("46.58");
bigDecimal = bigDecimal.setScale(1, RoundingMode.HALF_UP); // bigDecimal == 46.6
bigDecimal = bigDecimal.setScale(2, RoundingMode.UNNECESSARY); // bigDecimal == 46.60
英文:
You first need to round to 1 decimal place using standard half-up RoundingMode
and afterwards increase the scale to 2 again:
BigDecimal bigDecimal = new BigDecimal("46.58");
bigDecimal = bigDecimal.setScale(1, RoundingMode.HALF_UP); // bigDecimal == 46.6
bigDecimal = bigDecimal.setScale(2, RoundingMode.UNNECESSARY); // bigDecimal == 46.60
答案2
得分: 0
以下解决方案适用于我。
BigDecimal bigDecimal = new BigDecimal("46.58");
bigDecimal = bigDecimal.setScale(1, RoundingMode.HALF_UP);
bigDecimal = bigDecimal.setScale(2, RoundingMode.UNNECESSARY);
double d = bigDecimal.doubleValue();
String valstr = String.format("%.2f%n", d);
System.out.println(valstr);
英文:
below solution worked for me.
BigDecimal bigDecimal = new BigDecimal("46.58");
bigDecimal = bigDecimal.setScale(1, RoundingMode.HALF_UP);
bigDecimal = bigDecimal.setScale(2, RoundingMode.UNNECESSARY);
double d = bigDecimal.doubleValue();
String valstr = String.format("%.2f%n", d);
System.out.println(valstr);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论