aboutsummaryrefslogtreecommitdiff
path: root/src/utilmoneystr.cpp
diff options
context:
space:
mode:
authorWladimir J. van der Laan <laanwj@gmail.com>2014-08-21 16:11:09 +0200
committerWladimir J. van der Laan <laanwj@gmail.com>2014-08-26 13:25:22 +0200
commitad49c256c33bfe4088fd3c7ecb7d28cb81a8fc70 (patch)
treec4152c73cf6a424a882a125fa89c59ee6869bb86 /src/utilmoneystr.cpp
parentf841aa2892ffd97d564deee103555149d9fbcd9a (diff)
downloadbitcoin-ad49c256c33bfe4088fd3c7ecb7d28cb81a8fc70.tar.xz
Split up util.cpp/h
Split up util.cpp/h into: - string utilities (hex, base32, base64): no internal dependencies, no dependency on boost (apart from foreach) - money utilities (parsesmoney, formatmoney) - time utilities (gettime*, sleep, format date): - and the rest (logging, argument parsing, config file parsing) The latter is basically the environment and OS handling, and is stripped of all utility functions, so we may want to rename it to something else than util.cpp/h for clarity (Matt suggested osinterface). Breaks dependency of sha256.cpp on all the things pulled in by util.
Diffstat (limited to 'src/utilmoneystr.cpp')
-rw-r--r--src/utilmoneystr.cpp75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/utilmoneystr.cpp b/src/utilmoneystr.cpp
new file mode 100644
index 0000000000..1bd48d8d4c
--- /dev/null
+++ b/src/utilmoneystr.cpp
@@ -0,0 +1,75 @@
+#include "utilmoneystr.h"
+
+#include "core.h"
+#include "tinyformat.h"
+
+using namespace std;
+
+string FormatMoney(int64_t n, bool fPlus)
+{
+ // Note: not using straight sprintf here because we do NOT want
+ // localized number formatting.
+ int64_t n_abs = (n > 0 ? n : -n);
+ int64_t quotient = n_abs/COIN;
+ int64_t remainder = n_abs%COIN;
+ string str = strprintf("%d.%08d", quotient, remainder);
+
+ // Right-trim excess zeros before the decimal point:
+ int nTrim = 0;
+ for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
+ ++nTrim;
+ if (nTrim)
+ str.erase(str.size()-nTrim, nTrim);
+
+ if (n < 0)
+ str.insert((unsigned int)0, 1, '-');
+ else if (fPlus && n > 0)
+ str.insert((unsigned int)0, 1, '+');
+ return str;
+}
+
+
+bool ParseMoney(const string& str, int64_t& nRet)
+{
+ return ParseMoney(str.c_str(), nRet);
+}
+
+bool ParseMoney(const char* pszIn, int64_t& nRet)
+{
+ string strWhole;
+ int64_t nUnits = 0;
+ const char* p = pszIn;
+ while (isspace(*p))
+ p++;
+ for (; *p; p++)
+ {
+ if (*p == '.')
+ {
+ p++;
+ int64_t nMult = CENT*10;
+ while (isdigit(*p) && (nMult > 0))
+ {
+ nUnits += nMult * (*p++ - '0');
+ nMult /= 10;
+ }
+ break;
+ }
+ if (isspace(*p))
+ break;
+ if (!isdigit(*p))
+ return false;
+ strWhole.insert(strWhole.end(), *p);
+ }
+ for (; *p; p++)
+ if (!isspace(*p))
+ return false;
+ if (strWhole.size() > 10) // guard against 63 bit overflow
+ return false;
+ if (nUnits < 0 || nUnits > COIN)
+ return false;
+ int64_t nWhole = atoi64(strWhole);
+ int64_t nValue = nWhole*COIN + nUnits;
+
+ nRet = nValue;
+ return true;
+}