I want to extract just decimal part as a integer but it wasn't that easy as I thought. While searching I found that float/decimal
aren't the things that we can trust upon.
Is floating point math broken? Here I got answer why they don't work as expected but how exactly can I get decimal part as number isn't mentioned. For Now just upto two decimals
double number = 43475.1;
int integerNumber = number;//implicit
double difference = number-integerNumber;
int floatingNumber = difference*100;
std::cout<<"NUMBER = "<<number<<"\nintegerNumber = "<<integerNumber;
std::cout<<"\nDIFFERENCE INLINE "<< number-integerNumber<<"\nDIFFERENCE CALCULATED "<<difference;
std::cout<<"\nDIFFERENCE num " << floatingNumber;
Here the output is
NUMBER = 43475.1
integerNumber = 43475
DIFFERENCE INLINE 0.1
DIFFERENCE INT 0.1
DIFFERENCE num 9
How can I get 10
instead of 9
. I used a hack but I am not really convinced with my own answer
std::string str = std::to_string(difference);
int ans = atof(str.c_str())*100;
std::cout<<"\n\nAFTER CONVERSIONS::: \n";
std::cout<<str<<" and realDecimal= "<<ans;
This will result in
AFTER CONVERSIONS:::
0.100000 and realDecimal= 10
This works but are there better solution than converting to string and again back to integer???