Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

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