Created
February 23, 2023 20:06
-
-
Save RomanRobot/3566d9a50117e96add90eed528538658 to your computer and use it in GitHub Desktop.
Converts a double to an SI string. Converted to C++ from https://stackoverflow.com/a/12181661/719528.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Unicode `μ` for micro (10e-6) | |
std::wstring to_si_wstring(double number, int precision) | |
{ | |
std::wostringstream ss; | |
ss << std::setprecision(precision); | |
if (number != 0.0) | |
{ | |
static const std::array<wchar_t, 17> prefixes = { 'y', 'z', 'a', 'f', 'p', 'n', L'\u03bc', 'm', L'\u200b', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' }; | |
static const size_t zero_degree_index = 8; | |
int degree = (int)floor(log10(fabs(number)) / 3); | |
double scaled = number * pow(1000, -degree); | |
ss << scaled << prefixes[degree + zero_degree_index]; | |
} | |
else | |
{ | |
ss << 0.0; | |
} | |
return ss.str(); | |
} | |
// Non-Unicode `u` for micro (10e-6) | |
std::string to_si_string(double number, int precision) | |
{ | |
std::ostringstream ss; | |
ss << std::setprecision(precision); | |
if (number != 0.0) | |
{ | |
static const std::array<char, 17> prefixes = { 'y', 'z', 'a', 'f', 'p', 'n', 'u', 'm', ' ', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' }; | |
static const size_t zero_degree_index = 8; | |
int degree = (int)floor(log10(fabs(number)) / 3); | |
double scaled = number * pow(1000, -degree); | |
ss << scaled; | |
if (degree != 0) | |
{ | |
ss << prefixes[degree + zero_degree_index]; | |
} | |
} | |
else | |
{ | |
ss << 0.0; | |
} | |
return ss.str(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment