round double to 0.5

前端 未结 2 988
醉梦人生
醉梦人生 2021-02-20 03:42

i have a result \"1.444444\" and i want to round this result to \"1.5\" this is the code i use :

a.text = String(round(13000 / 9000.0))

but thi

2条回答
  •  甜味超标
    2021-02-20 04:15

    x = 13000 / 9000.0;
    
    denominator = 2;
    a.text = String(round(x*denominator )/denominator );
    

    First convert 1.444 to 2.888, then round to 3.0 and then divide by 2 to get 1.5. In this case, the denominator of 0.5 is 2 (i.e. 1/2). If you want to round to nearest quarter (0.25,0.5, 0.75, 0.00), then denominator=4

    I Should point out that this works perfectly if the denominator is a power of 2. If it is not, say denominator=3, then you can get weird answers like 1.99999999 instead of 2 for particular values.

提交回复
热议问题