Rounding a double number up to the tenths place [duplicate]

眉间皱痕 提交于 2019-12-22 17:53:32

问题


Possible Duplicate:
round() for float in C++

Ok suppose I had the number 8.47434. I want to round it up to 8.5 and to 1 decimal place. How would I go about doing this in C++


回答1:


Multiply by 10, round and divide by 10 again.

Example:

round(10 * 8.47434f) / 10;

Edit:

OK, I just found out that round() is not always present in math.h.

The above works in gcc and icl (with Microsoft's libraries), but not in tcc.

floor(), however, is part of the standard libraries. So to round, we can add 0.5 and use floor().

Example:

floor(10 * 8.47434f + 0.5f) / 10;



回答2:


std::floor(d)+std::floor((d-std::floor(d))*10.0+0.5)/10.0

Doing it this way won't lose precision, as opposed to the other answers which multiply the original double by 10. (d would be your number by the way)

Be forewarned though: floating point numbers can't represent anything. With doubles: 1.35 will round to 1.3999999999999999; 123.34 will be represented as 123.34999999999999 in the first place causing it to round down to 123.3 instead of the intended 123.4; etc




回答3:


You could multiple by 10 add 0.5 cast to an int and divide by ten.

if the number is negative subtract 0.5 or multiply and divide by negative ten.



来源:https://stackoverflow.com/questions/7870003/rounding-a-double-number-up-to-the-tenths-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!