Raven Core  3.0.0
P2P Digital Currency
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 // Copyright (c) 2017-2019 The Raven 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 std::string FormatMoney(const CAmount& n)
14 {
15  // Note: not using straight sprintf here because we do NOT want
16  // localized number formatting.
17  int64_t n_abs = (n > 0 ? n : -n);
18  int64_t quotient = n_abs/COIN;
19  int64_t remainder = n_abs%COIN;
20  std::string str = strprintf("%d.%08d", quotient, remainder);
21 
22  // Right-trim excess zeros before the decimal point:
23  int nTrim = 0;
24  for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
25  ++nTrim;
26  if (nTrim)
27  str.erase(str.size()-nTrim, nTrim);
28 
29  if (n < 0)
30  str.insert((unsigned int)0, 1, '-');
31  return str;
32 }
33 
34 
35 bool ParseMoney(const std::string& str, CAmount& nRet)
36 {
37  return ParseMoney(str.c_str(), nRet);
38 }
39 
40 bool ParseMoney(const char* pszIn, CAmount& nRet)
41 {
42  std::string strWhole;
43  int64_t nUnits = 0;
44  const char* p = pszIn;
45  while (isspace(*p))
46  p++;
47  for (; *p; p++)
48  {
49  if (*p == '.')
50  {
51  p++;
52  int64_t nMult = CENT*10;
53  while (isdigit(*p) && (nMult > 0))
54  {
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 }
#define strprintf
Definition: tinyformat.h:1054
int64_t CAmount
Amount in corbies (Can be negative)
Definition: amount.h:13
bool ParseMoney(const std::string &str, CAmount &nRet)
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
int64_t atoi64(const char *psz)