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