#include <iostream>
#include <sstream>
#include <math.h>
using namespace std;
int GetDecimalsUsingString( float number );
int GetDecimals( float number, int num_decimals );
int main() {
float x = -1234.5678;
int x1 = (int) x; // which would return 1234 great.
float remainder = x - static_cast< float > ( x1 );
std::cout << "Original : " << x << std::endl;
std::cout << "Before comma : " << x1 << std::endl;
std::cout << "Remainder : " << remainder << std::endl;
// "Ugly" way using std::stringstream and std::string
int res_string = GetDecimalsUsingString( remainder );
// Nicer, but requires that you specify number of decimals
int res_num_decimals = GetDecimals( remainder, 6 );
std::cout << "Result using string : " << res_string << std::endl;
std::cout << "Result using known number of decimals : " << res_num_decimals << std::endl;
return 0;
}
int GetDecimalsUsingString( float number )
{
// Put number in a stringstream
std::stringstream ss;
ss << number;
// Put content of stringstream into a string
std::string str = ss.str();
// Remove the first part of the string ( minus symbol, 0 and decimal point)
if ( number < 0.0 )
str = str.substr( 3, str.length() - 1);
else
str = str.substr( 2, str.length() - 1);
// Convert string back to int
int ret = std::strtol( str.c_str(), NULL, 10 );
/// Preserve sign
if ( number < 0 )
ret *= -1;
return ret;
}
int GetDecimals( float number, int num_decimals )
{
int decimal_multiplier = pow( 10, num_decimals );
int result = number * decimal_multiplier;
return result;
}