/npk/cli/helper_commify.hpp

http://npk.googlecode.com/ · C++ Header · 56 lines · 52 code · 4 blank · 0 comment · 20 complexity · 5986302acbb195991e47ece607d7a8be MD5 · raw file

  1. #pragma warning( disable : 4996 )
  2. #ifdef NPK_PLATFORM_LINUX
  3. #include <string.h>
  4. #endif
  5. void commify(double val, char *buf, int round, int comma = 3)
  6. {
  7. char temp[255];
  8. sprintf( temp, "%f", val );
  9. char *tc = &temp[0], *bc = buf;
  10. char *pc = strchr( temp, '.' );
  11. int underpoint = -1;
  12. while( *tc != '\0' )
  13. {
  14. if( ( *tc >= '0' ) && ( *tc <= '9' ) )
  15. {
  16. *bc = *tc;
  17. ++bc;
  18. if( underpoint >= 0 )
  19. {
  20. ++underpoint;
  21. if( round == underpoint )
  22. break;
  23. }
  24. }
  25. else if( *tc == '.' )
  26. {
  27. if( round == 0 )
  28. break;
  29. else
  30. {
  31. *bc = '.';
  32. ++bc;
  33. underpoint = 0;
  34. }
  35. }
  36. else if( *tc == '-' )
  37. {
  38. *bc = '.';
  39. ++bc;
  40. }
  41. ++tc;
  42. if( underpoint < 0 )
  43. {
  44. if( ( ( ( pc - tc ) % comma ) == 0 ) && ( tc != pc ) )
  45. {
  46. *bc = ',';
  47. ++bc;
  48. }
  49. }
  50. }
  51. *bc = '\0';
  52. }