fork download
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. const int intToFloatAndBack( const int intVal )
  5. {
  6. const float floatVal = static_cast<float>(intVal);
  7. return static_cast<int>(floatVal);
  8. }
  9.  
  10. const float floatToIntAndBack(const float floatVal, const int precision = 3 )
  11. {
  12. const unsigned char power = pow( 10, precision );
  13. const int intVal = floatVal * power;
  14. return intVal / static_cast<float>(power);
  15. }
  16.  
  17. int main ( void )
  18. {
  19. //Example of saving ints as floats failing
  20. std::cout << intToFloatAndBack( 123456789 ) << std::endl;
  21.  
  22. //Example of saving floats as int succeeding (Will of course fail for some inputs)
  23. std::cout << floatToIntAndBack( 123.456f ) << std::endl;
  24. return 0;
  25. }
Success #stdin #stdout 0.01s 5620KB
stdin
Standard input is empty
stdout
123456792
123.455