You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utilmoneystr.cpp 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #include "utilmoneystr.h"
  6. #include "core.h"
  7. #include "tinyformat.h"
  8. #include "utilstrencodings.h"
  9. using namespace std;
  10. string FormatMoney(const CAmount& n, bool fPlus)
  11. {
  12. // Note: not using straight sprintf here because we do NOT want
  13. // localized number formatting.
  14. int64_t n_abs = (n > 0 ? n : -n);
  15. int64_t quotient = n_abs/COIN;
  16. int64_t remainder = n_abs%COIN;
  17. string str = strprintf("%d.%08d", quotient, remainder);
  18. // Right-trim excess zeros before the decimal point:
  19. int nTrim = 0;
  20. for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
  21. ++nTrim;
  22. if (nTrim)
  23. str.erase(str.size()-nTrim, nTrim);
  24. if (n < 0)
  25. str.insert((unsigned int)0, 1, '-');
  26. else if (fPlus && n > 0)
  27. str.insert((unsigned int)0, 1, '+');
  28. return str;
  29. }
  30. bool ParseMoney(const string& str, CAmount& nRet)
  31. {
  32. return ParseMoney(str.c_str(), nRet);
  33. }
  34. bool ParseMoney(const char* pszIn, CAmount& nRet)
  35. {
  36. string strWhole;
  37. int64_t nUnits = 0;
  38. const char* p = pszIn;
  39. while (isspace(*p))
  40. p++;
  41. for (; *p; p++)
  42. {
  43. if (*p == '.')
  44. {
  45. p++;
  46. int64_t nMult = CENT*10;
  47. while (isdigit(*p) && (nMult > 0))
  48. {
  49. nUnits += nMult * (*p++ - '0');
  50. nMult /= 10;
  51. }
  52. break;
  53. }
  54. if (isspace(*p))
  55. break;
  56. if (!isdigit(*p))
  57. return false;
  58. strWhole.insert(strWhole.end(), *p);
  59. }
  60. for (; *p; p++)
  61. if (!isspace(*p))
  62. return false;
  63. if (strWhole.size() > 10) // guard against 63 bit overflow
  64. return false;
  65. if (nUnits < 0 || nUnits > COIN)
  66. return false;
  67. int64_t nWhole = atoi64(strWhole);
  68. CAmount nValue = nWhole*COIN + nUnits;
  69. nRet = nValue;
  70. return true;
  71. }