The problem I'm facing is because I'm using a library that when fed a float
, it does something inside that is converting the float to double and adding a lot of decimals to the number which is not right. I mean, is right according to how doubles and floats are represented and what naturally happens when you cast, but it is not right for my application. I have 16.3
as float
and I need that to be 16.3
as double
.
I'm trying to cast the float to double BEFORE passing the value to the library to have control over that conversion but so far I haven't found a straightforward way of doing so. I just want to know if it is possible to cast a 16.3 from float
to double
and have the same 16.3 as a result.
float f_var = 16.3; // f_var is 16.3
double d_var = (double)f_var; // d_var shall be also 16.3, not 16.299999237060547
Is there even a proper way of doing this in C++? Or I would have to do something like:
char float_buf[10];
float f_var = 16.3;
sprintf(float_buf, "%.2f", f_var);
double d_var = atof(float_buf);
Because that works, but I'd like to see if there is a "proper" way of doing this in c++.
There is this response in SO with another proposed solution but it involves multiplication and a division that I would like to avoid as well.
This is not for displaying or any input/output operation or converting to a string, I know how to do that and there is a lot of information about it. Additionally, I'm not trying to understand "why" this happens, there is a lot of information about that as well.
Also, most of the answers in SO that may cause this question to be marked as duplicate are not for C++, they are mostly for C#, Java JS, Objective C, etc. For the few I found for C/C++, most of them are dealing with this issue for IO with printf
or cout
and the others only explain why this happens which is also not useful. If you have indeed a duplicate for this exactly in C++ then please indicate. I'll be happy for this to be flagged as duplicate if it really is.
Thanks!