]>
Commit | Line | Data |
---|---|---|
4d04492b | 1 | // Copyright (c) 2009-2010 Satoshi Nakamoto |
f914f1a7 | 2 | // Copyright (c) 2009-2014 The Bitcoin Core developers |
c63a73d1 | 3 | // Distributed under the MIT software license, see the accompanying |
4d04492b PK |
4 | // file COPYING or http://www.opensource.org/licenses/mit-license.php. |
5 | ||
ad49c256 WL |
6 | #include "utilmoneystr.h" |
7 | ||
d2270111 | 8 | #include "primitives/transaction.h" |
ad49c256 | 9 | #include "tinyformat.h" |
85c579e3 | 10 | #include "utilstrencodings.h" |
ad49c256 WL |
11 | |
12 | using namespace std; | |
13 | ||
a372168e | 14 | string FormatMoney(const CAmount& n, bool fPlus) |
ad49c256 WL |
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 | 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 | ||
a372168e | 38 | bool ParseMoney(const string& str, CAmount& nRet) |
ad49c256 WL |
39 | { |
40 | return ParseMoney(str.c_str(), nRet); | |
41 | } | |
42 | ||
a372168e | 43 | bool ParseMoney(const char* pszIn, CAmount& nRet) |
ad49c256 WL |
44 | { |
45 | string strWhole; | |
46 | int64_t nUnits = 0; | |
47 | const char* p = pszIn; | |
48 | while (isspace(*p)) | |
49 | p++; | |
50 | for (; *p; p++) | |
51 | { | |
52 | if (*p == '.') | |
53 | { | |
54 | p++; | |
55 | int64_t nMult = CENT*10; | |
56 | while (isdigit(*p) && (nMult > 0)) | |
57 | { | |
58 | nUnits += nMult * (*p++ - '0'); | |
59 | nMult /= 10; | |
60 | } | |
61 | break; | |
62 | } | |
63 | if (isspace(*p)) | |
64 | break; | |
65 | if (!isdigit(*p)) | |
66 | return false; | |
67 | strWhole.insert(strWhole.end(), *p); | |
68 | } | |
69 | for (; *p; p++) | |
70 | if (!isspace(*p)) | |
71 | return false; | |
72 | if (strWhole.size() > 10) // guard against 63 bit overflow | |
73 | return false; | |
74 | if (nUnits < 0 || nUnits > COIN) | |
75 | return false; | |
76 | int64_t nWhole = atoi64(strWhole); | |
a372168e | 77 | CAmount nValue = nWhole*COIN + nUnits; |
ad49c256 WL |
78 | |
79 | nRet = nValue; | |
80 | return true; | |
81 | } |