fork(1) download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <math.h>
  4. using namespace std;
  5.  
  6. int GetDecimalsUsingString( float number );
  7. int GetDecimals( float number, int num_decimals );
  8.  
  9. int main() {
  10. float x = -1234.5678;
  11. int x1 = (int) x; // which would return 1234 great.
  12. float remainder = x - static_cast< float > ( x1 );
  13. std::cout << "Original : " << x << std::endl;
  14. std::cout << "Before comma : " << x1 << std::endl;
  15. std::cout << "Remainder : " << remainder << std::endl;
  16.  
  17. // "Ugly" way using std::stringstream and std::string
  18. int res_string = GetDecimalsUsingString( remainder );
  19.  
  20. // Nicer, but requires that you specify number of decimals
  21. int res_num_decimals = GetDecimals( remainder, 6 );
  22.  
  23. std::cout << "Result using string : " << res_string << std::endl;
  24. std::cout << "Result using known number of decimals : " << res_num_decimals << std::endl;
  25. return 0;
  26. }
  27.  
  28. int GetDecimalsUsingString( float number )
  29. {
  30. // Put number in a stringstream
  31. std::stringstream ss;
  32. ss << number;
  33.  
  34. // Put content of stringstream into a string
  35. std::string str = ss.str();
  36.  
  37. // Remove the first part of the string ( minus symbol, 0 and decimal point)
  38. if ( number < 0.0 )
  39. str = str.substr( 3, str.length() - 1);
  40. else
  41. str = str.substr( 2, str.length() - 1);
  42.  
  43. // Convert string back to int
  44. int ret = std::strtol( str.c_str(), NULL, 10 );
  45.  
  46. /// Preserve sign
  47. if ( number < 0 )
  48. ret *= -1;
  49.  
  50. return ret;
  51. }
  52. int GetDecimals( float number, int num_decimals )
  53. {
  54. int decimal_multiplier = pow( 10, num_decimals );
  55. int result = number * decimal_multiplier;
  56.  
  57. return result;
  58. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Original : -1234.57
Before comma : -1234
Remainder : -0.567749
Result using string : -567749
Result using known number of decimals : -567749