I want to round a float to maximum 4 decimals places. It mean 0.333333333 will be 0.3333, but 0.33 is still 0.33
-
2Possible duplicate of [round() for float in C++](https://stackoverflow.com/questions/485525/round-for-float-in-c) – quamrana Mar 08 '19 at 13:40
-
Rounding as application logic, or rounding during conversion to string (to show in UI)? This two things are completely different issue! – Marek R Mar 08 '19 at 13:54
-
Also what do you expect if input is: `33333.333` or `0.00000333333333`. – Marek R Mar 08 '19 at 14:01
-
Hmm let me give you some examples If input is 0.12346, output will be 0.1235 0.42 still be 0.42 0.523 still be 0.523 – Tiến Trần Mar 08 '19 at 14:17
-
Are you looking to round output, or looking to round the values in your variables? The first is sensible, but you seem to be asking for the second. The answers are different depending on which you want to do. – john Mar 08 '19 at 14:50
-
@TiếnTrần edit your question adding more test data what you need. Take into account very big or very small values, not just those between `0.1` and `1.0`. Also state clearly if you need print value or just round it for further calculations. – Marek R Mar 08 '19 at 15:08
-
note that depending on context some answers are WRONG on not and some useless. For example @einpoklum answer can be best (in case of currency) or total overkill. All depending on missing context. – Marek R Mar 08 '19 at 15:13
-
@MarekR: I have two answers, actually. But you're right in the sense that OP should have described the context. – einpoklum Mar 08 '19 at 15:40
5 Answers
Use the std::round()
function
The C++ standard library offers functions for performing rounding. For float
s, it is:
float round ( float arg );
this will round arg
to the nearest integral value. Now, you want a different decimal resolution. So don't round your value, round your value times 10000, so your singles digit is now the former 0.0001 digit. Or more generally:
float my_round(
float x,
int num_decimal_precision_digits)
{
float power_of_10 = std::pow(10, num_decimal_precision_digits);
return std::round(x * power_of_10) / power_of_10;
}
Note that there may be accuracy issues, as floating-point computations and representations are only accurate to within a certain number of digits, and in my_round
we have at least four sources of such inaccuracy: The power-of-10 calculation, the multiplication, the devision and the actual rounding.

- 118,144
- 57
- 340
- 684
-
Is there another way doing that without using 'auto'? By the way thank you so much <3 – Tiến Trần Mar 08 '19 at 14:08
-
@TiếnTrần use `double` instead of `auto`, but I highly suggest you switch to at least `c++11` and actually use `auto`. – Fureeish Mar 08 '19 at 14:10
-
@TiếnTrần: You don't need the `auto`, you can use `float`. Or you can use `double`s all over to reduce inaccuracies. – einpoklum Mar 08 '19 at 14:12
-
strange that `setprecision` does rounding for output but there is no built in way to choose the number of digits for `round` – 463035818_is_not_an_ai Mar 08 '19 at 14:13
-
@user463035818: It's because `round()` comes from the C standard library, I guess. But you would have thought someone might have proposed that by now, yeah. – einpoklum Mar 08 '19 at 14:14
Cast it into a fixed-point type
If you want to have your results rounded, with a fixed number of decimal digits, you're hinting that you don't really need the "floating" aspect of floating point numbers. Well, in this case, cast your value to a type which represents such numbers. Essentially, that would be a (run-time-variable) integer numerator and a compile-time-fixed denominator (which in your case would be 10,000).
There's an old question here on the site about doing fixed-point math:
What's the best way to do fixed-point math?
but I would suggest you consider the CNL library as something recent/popular. Also, several proposals have been made to add fixed-point types to the standard library. I don't know which one is the farthest advance, but have a look at this one: Fixed-Point Real Numbers by John McFarlane.
Back to your specific case: Fixed-point types can typically be constructed from floating-point ones. Just do that.

- 118,144
- 57
- 340
- 684
Here is a solution, for example:
float ret = float(round(0.333333333 * 10000)) / 10000)
You can write it as a function. Maybe there would be a better way?

- 630
- 3
- 9
-
-
1this will work for `0.33333333` but not for `3333.3333` or `0.00003333`. – Marek R Mar 08 '19 at 14:00
Assuming you need print rounded number, this is one of a proper solutions:
cout << setprecision(4) << x << '\n';
std::setprecision documentation.
Until more details are not provided it is impossible to provide a better answer.
Please note if you are planing to round number x
then print it, it will end with big headache, since some corner cases can produce much longer results then expected.

- 32,568
- 6
- 55
- 140
-
My impression is that you need to specify to used fixed precision, in order to be able to specify nr of digits after the decimal point. See http://www.cplusplus.com/reference/ios/ios_base/precision/ – Erik Alapää Mar 08 '19 at 14:29
-
@ErikAlapää is correct. In order to get the desired behavior, `std::fixed << std::setprecision(n)` must be used. Otherwise, there will be `n` digits of total precision. Using `std::fixed` specifies `n` digits of _decimal_ precision. – Richard Mar 08 '19 at 14:32
-
@Richard Thank you for comment. I forgot to add that scientific notation also has same property as fixed, i.e. setting precision actually sets nr of digits after decimal point. – Erik Alapää Mar 08 '19 at 14:52
-
@Richard where in question do you see detailed description of desired behavior? This is why I've wrote `this is one of a proper solutions`. – Marek R Mar 08 '19 at 15:00
-
@MarekR Although it is ambiguous whether the original post intended to print or round to a value, I think the 'desired behavior' for rounding a floating point number to "4 decimals places" is to _round the float to 4 decimal places_. Using `setprecision` without `std::fixed` will truncate the decimal portion for numbers such as `1234.5678` (which gets printed as `1235` in your original answer). – Richard Mar 08 '19 at 15:10
Use _vsnprintf
I think the best solution for this is to just format the string. Because what if we don't need to output this number to the console, but save it in a std::string
variable or char[]
or something like that. This solution is flexible because it is the same if you output a number to the console and used the std::setprecision()
function, but also returning this number to char[]
.
So for this I used _vsnprintf
and va_list
. All it does is format the string as needed, in this case float value.
int FormatString(char* buf, size_t buf_size, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
int w = _vsnprintf(buf, buf_size, fmt, args);
va_end(args);
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
int FormatStringFloat(char* buf, int buf_size, const void* p_data, const char* format) {
return FormatString(buf, buf_size, format, *(const float*)p_data);
}
Example
#include "iostream"
#include "string"
#define ARRAY_SIZE(_ARR) ((int)(sizeof(_ARR) / sizeof(*(_ARR))))
int main() {
float value = 3.343535f;
char buf[64];
FormatStringFloat(buf, ARRAY_SIZE(buf), (void*)&value, "%.2f");
std::cout << std::string(buf) << std::endl;
return 0;
}
So by using "%.2f" we get from the 3.343535 => 3.34.

- 49,934
- 160
- 51
- 83

- 35
- 7