简体   繁体   中英

How can I limit the amount of decimal places for a calculated float value?

When I calculated 5/2 the result is 2.500000, so I was wondering how I can limit the result of the float value to 2.50 instead. I am not using cout setprecision() or the fixed statement because I need the actual result of the arithmetic value to have only 2 decimal places.

如果您不想使用某些小数位,那么使用ceil()floor()round()怎么样?

First of all, 2/5 gives 2 because writing it like this will do integer division. Only 2.0f/5.0f will give you back a float.

Secondly, the only thing std::setprecision does is modify how many digits are displayed on the console when you do std::cout , it doesnt change the value of your variable or expression.

If you want to round your result to say one decimal place and not use standard functions, you could do something like

float a = 3.1415;
float b = ((int)(a*10+0.5))/10.0       // b is a rounded to one decimal place

but if you set std::setprecision to say 5 decimal places, it will still show you all the zeros after the last decimal place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM