Guillaume Paris
Guillaume Paris

Reputation: 10539

have a nice representation of a string from a double

I have a double 1.4291400000000001 I want to have a string representation of that double.

What is the best/standard way to get 1.42914

Upvotes: 3

Views: 147

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361612

It's not guaranteed to have a double to have exactly this value : 1.4291400000000001. It could be a little greater than that or little smaller than that. Much less like to be exactly that.

After this fact, I can say that there is no best way to get 1.42914 from that. You might get 1.42913 instead, as the actual double value might be : 1.4291399999999999 instead of the above value.

Read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Upvotes: 2

Kiril Kirov
Kiril Kirov

Reputation: 38173

What about:

std::stringstream ss;
ss << std::fixed << std::setprecision( N ) << double_number;
// ss.str() gives you the string 

Upvotes: 10

Related Questions