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.0KB

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