在Java中对小数部分进行向上取整或四舍五入。

huangapple go评论66阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2020年4月7日 21:59:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/61081764.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定