Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2014 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 :
8 : #include "primitives/transaction.h"
9 : #include "tinyformat.h"
10 : #include "utilstrencodings.h"
11 :
12 : using namespace std;
13 :
14 15403 : std::string FormatMoney(const CAmount& n)
15 : {
16 : // Note: not using straight sprintf here because we do NOT want
17 : // localized number formatting.
18 15403 : int64_t n_abs = (n > 0 ? n : -n);
19 15403 : int64_t quotient = n_abs/COIN;
20 15403 : int64_t remainder = n_abs%COIN;
21 15403 : string str = strprintf("%d.%08d", quotient, remainder);
22 :
23 : // Right-trim excess zeros before the decimal point:
24 15403 : int nTrim = 0;
25 315152 : for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
26 90799 : ++nTrim;
27 15403 : if (nTrim)
28 30804 : str.erase(str.size()-nTrim, nTrim);
29 :
30 15403 : if (n < 0)
31 1 : str.insert((unsigned int)0, 1, '-');
32 15403 : return str;
33 : }
34 :
35 :
36 8 : bool ParseMoney(const string& str, CAmount& nRet)
37 : {
38 8 : return ParseMoney(str.c_str(), nRet);
39 : }
40 :
41 28 : bool ParseMoney(const char* pszIn, CAmount& nRet)
42 : {
43 : string strWhole;
44 28 : int64_t nUnits = 0;
45 28 : const char* p = pszIn;
46 56 : while (isspace(*p))
47 0 : p++;
48 78 : for (; *p; p++)
49 : {
50 102 : if (*p == '.')
51 : {
52 24 : p++;
53 24 : int64_t nMult = CENT*10;
54 124 : while (isdigit(*p) && (nMult > 0))
55 : {
56 76 : nUnits += nMult * (*p++ - '0');
57 76 : nMult /= 10;
58 : }
59 : break;
60 : }
61 78 : if (isspace(*p))
62 : break;
63 78 : if (!isdigit(*p))
64 : return false;
65 78 : strWhole.insert(strWhole.end(), *p);
66 : }
67 0 : for (; *p; p++)
68 0 : if (!isspace(*p))
69 : return false;
70 28 : if (strWhole.size() > 10) // guard against 63 bit overflow
71 : return false;
72 27 : if (nUnits < 0 || nUnits > COIN)
73 : return false;
74 27 : int64_t nWhole = atoi64(strWhole);
75 27 : CAmount nValue = nWhole*COIN + nUnits;
76 :
77 27 : nRet = nValue;
78 27 : return true;
79 330 : }
|