Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float to string with precision & number of decimal digits specified?

How do you convert a float to a string in C++ while specifying the precision & number of decimal digits?

For example: 3.14159265359 -> "3.14"

like image 871
Shannon Matthews Avatar asked Mar 22 '15 22:03

Shannon Matthews


People also ask

Can you convert a float to a string?

We can convert float to String in java using String. valueOf() and Float. toString() methods.

Can you convert float to string Python?

We can convert float to a string easily using str() function.

How do you change the precision of a float?

Floats have a static, fixed precision. You can't change it. What you can sometimes do, is round the number.

Can we convert float to string in C++?

We can convert float and double to string using the C++11 std::to_string() function.


2 Answers

A typical way would be to use stringstream:

#include <iomanip> #include <sstream>  double pi = 3.14159265359; std::stringstream stream; stream << std::fixed << std::setprecision(2) << pi; std::string s = stream.str(); 

See fixed

Use fixed floating-point notation

Sets the floatfield format flag for the str stream to fixed.

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

and setprecision.


For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.

Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:

#include <array> #include <charconv>  double pi = 3.14159265359; std::array<char, 128> buffer; auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,                                std::chars_format::fixed, 2); if (ec == std::errc{}) {     std::string s(buffer.data(), ptr);     // .... } else {     // error handling } 
like image 137
AlexD Avatar answered Sep 21 '22 01:09

AlexD


The customary method for doing this sort of thing is to "print to string". In C++ that means using std::stringstream something like:

std::stringstream ss; ss << std::fixed << std::setprecision(2) << number; std::string mystring = ss.str(); 
like image 41
Mats Petersson Avatar answered Sep 20 '22 01:09

Mats Petersson