Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#include <util/moneystr.h>8#include <consensus/amount.h>9#include <tinyformat.h>10#include <util/strencodings.h>11#include <util/string.h>13#include <cstdint>14#include <optional>16using util::ContainsNUL;17using util::TrimString;19std::string FormatMoney(const CAmount n)20{21// Note: not using straight sprintf here because we do NOT want22// localized number formatting.23static_assert(COIN > 1);24int64_t quotient = n / COIN;25int64_t remainder = n % COIN;26if (n < 0) {27quotient = -quotient;28remainder = -remainder;29}30std::string str = strprintf("%d.%08d", quotient, remainder);32// Right-trim excess zeros before the decimal point:33int nTrim = 0;34for (int i = str.size()-1; (str[i] == '0' && IsDigit(str[i-2])); --i)35++nTrim;36if (nTrim)37str.erase(str.size()-nTrim, nTrim);39if (n < 0)40str.insert(uint32_t{0}, 1, '-');41return str;42}45std::optional<CAmount> ParseMoney(const std::string& money_string)46{47if (ContainsNUL(money_string)) {48return std::nullopt;49}50const std::string str = TrimString(money_string);51if (str.empty()) {52return std::nullopt;53}55std::string strWhole;56int64_t nUnits = 0;57const char* p = str.c_str();58for (; *p; p++)59{60if (*p == '.')61{62p++;63int64_t nMult = COIN / 10;64while (IsDigit(*p) && (nMult > 0))65{66nUnits += nMult * (*p++ - '0');67nMult /= 10;68}69break;70}71if (IsSpace(*p))72return std::nullopt;73if (!IsDigit(*p))74return std::nullopt;75strWhole.insert(strWhole.end(), *p);76}77if (*p) {78return std::nullopt;79}80if (strWhole.size() > 10) // guard against 63 bit overflow81return std::nullopt;82if (nUnits < 0 || nUnits > COIN)83return std::nullopt;84int64_t nWhole = LocaleIndependentAtoi<int64_t>(strWhole);85CAmount value = nWhole * COIN + nUnits;87if (!MoneyRange(value)) {88return std::nullopt;89}91return value;92}