How can I round a float (such as 37.777779) to two decimal places (37.78) in C?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Assuming you're talking about round the value for printing, then Andrew Coleson and AraK's answer are correct:
But note that if you're aiming to round the number to exactly 37.78 for internal use (eg to compare against another value), then this isn't a good idea, due to the way floating point numbers work: you usually don't want to do equality comparisons for floating point, instead use a target value +/- a sigma value. Or encode the number as a string with a known precision, and compare that.
See the link in Greg Hewgill's answer to a related question, which also covers why you shouldn't use floating point for financial calculations.
I made this macro for rounding float numbers. Add it in your header / being of file
Here is an example:
x equals 3.14 :)
If you just want to round the number for output purposes, then the
"%.2f"
format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.
As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.
For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.
In C++ (or in C with C-style casts), you could create the function:
Then
std::cout << showDecimals(37.777779,2);
would produce: 37.78.Obviously you don't really need to create all 5 variables in that function, but I leave them there so you can see the logic. There are probably simpler solutions, but this works well for me--especially since it allows me to adjust the number of digits after the decimal place as I need.
this function takes the number and precision and returns the rounded off number
it converts the floating point number into int by left shifting the point and checking for the greater than five condition.
If you want to write to C-string: