Rounding a double number up to the tenths place [d

2019-05-20 02:50发布

问题:

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.