开发者

Facing issues in doing round off in Java

开发者 https://www.devze.com 2023-03-06 21:00 出处:网络
I have to show the fund value to customers for the next 30 years in one of my application , but the issue is there are some decimal values present , so we have to do the round off those values so that

I have to show the fund value to customers for the next 30 years in one of my application , but the issue is there are some decimal values present , so we have to do the round off those values so that we will be c开发者_JAVA百科alculated properly .e.g we there are values like, 414.598940334717 , it should round off to 414.60 but it is not getting round off with this function till 414.61 according to the spreadsheet. I have written this method

BigDecimal bd = new BigDecimal(Double.toString(414.598940334717));

bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP );


try

  DecimalFormat twoDForm = new DecimalFormat("#.##");
  System.out.print(twoDForm.format(Double.valueOf("414.588940334717")));


I don't see your issue...

BigDecimal bd = new BigDecimal(Double.toString(414.598940334717));    
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP );
System.out.println("" + bd);

Output

414.60

My usual trick to do round-ups like this is to just use casting:

double d = 414.598940334717;
double rounded = (int)(d * 100 + 0.5) / 100.0;
System.out.println("" + rounded);

Output

414.6

0

精彩评论

暂无评论...
验证码 换一张
取 消