Double value to round up in Java

后端 未结 10 1915
我寻月下人不归
我寻月下人不归 2020-12-07 12:44

I have a double value = 1.068879335 i want to round it up with only two decimal values like 1.07.

I tried like this

DecimalFormat df=new         


        
10条回答
  •  粉色の甜心
    2020-12-07 13:25

    This is not possible in the requested way because there are numbers with two decimal places which can not be expressed exactly using IEEE floating point numbers (for example 1/10 = 0.1 can not be expressed as a Double or Float). The formatting should always happen as the last step before presenting the result to the user.

    I guess you are asking because you want to deal with monetary values. There is no way to do this reliably with floating-point numbers, you shoud consider switching to fixed-point arithmetics. This probably means doing all calculations in "cents" instead of "dollars".

提交回复
热议问题