Skip to content

Instantly share code, notes, and snippets.

@sleepdefic1t
Created January 17, 2020 01:39
Show Gist options
  • Save sleepdefic1t/d62d57f5137fce520bbe72c55c66cc34 to your computer and use it in GitHub Desktop.
Save sleepdefic1t/d62d57f5137fce520bbe72c55c66cc34 to your computer and use it in GitHub Desktop.
/*******************************************************************************
*
* Copyright (c) Simon Downey <[email protected]>
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
#ifndef NUM_TO_STRING_HPP
#define NUM_TO_STRING_HPP
#include <string>
inline const std::string NumToString(int64_t amount) {
if (amount == 0) {
return "0";
}
const uint8_t STRING_SIZE = 24U;
const char *STRING_TABLE = "0123456789";
uint64_t temp = amount < 0 ? -amount : amount;
std::string result;
result.reserve(STRING_SIZE);
while (temp != 0U) {
result += STRING_TABLE[temp % BASE_10];
temp /= BASE_10;
}
if (amount < 0) {
result.insert(result.end(), '-');
}
std::reverse(result.begin(), result.end());
return result;
}
inline const std::string NumToFloatString(int64_t amount, size_t decimals) {
std::string result = NumToString(amount);
if (decimals > result.length() - (amount < 0) - 1 ||
result == "0") {
return {};
}
if (decimals > 0) {
result.insert(result.end() - decimals , '.');
}
return result;
}
#endif //#define NUM_TO_STRING_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment