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