Skip to content

Instantly share code, notes, and snippets.

@JosephTLyons
Last active July 6, 2020 01:36
Show Gist options
  • Save JosephTLyons/1a3f92ad7b3674502c5d562d73dc0df4 to your computer and use it in GitHub Desktop.
Save JosephTLyons/1a3f92ad7b3674502c5d562d73dc0df4 to your computer and use it in GitHub Desktop.
A hacky way to get a string from a float in C++
// A hacky way to get a string from a float in C++
#include <iostream>
#include <math.h>
std::string float_to_string(const double& number, int precision)
{
int adjustment_int = pow(10, precision);
int intermediate_value = number * adjustment_int;
double truncated_float = intermediate_value / (double) adjustment_int;
std::string truncated_float_string = std::to_string(truncated_float);
while (truncated_float_string[truncated_float_string.size() - 1] == '0')
truncated_float_string.pop_back();
return truncated_float_string;
}
int main(int argc, const char * argv[])
{
float number = 23.92367345;
std::cout << float_to_string(number, 2) << std::endl;
float number_2 = 924.63491;
std::cout << float_to_string(number_2, 3) << std::endl;
float number_3 = -1.72346;
std::cout << float_to_string(number_3, 1) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment