Float to String conversion

M

Max

I did some searching on the subject, but still can't find the answer, so
thought I'd ask. I have a float that needs to be converted into a string
type. That float is always >= 0.00 and must have 2 numbers after the
decimal, even if those numbers are 00. What's the best way to go about this?
 
R

red floyd

Max said:
I did some searching on the subject, but still can't find the answer, so
thought I'd ask. I have a float that needs to be converted into a string
type. That float is always >= 0.00 and must have 2 numbers after the
decimal, even if those numbers are 00. What's the best way to go about
this?

std::eek:stringstream
 
J

John Harrison

red floyd said:
std::eek:stringstream

std::eek:stringstream buf;
buf << std::fixed << std::setprecision(2) << my_float;
std::string my_string = buf.str();

(untested)

john

PS using floating point values to represent money is a design error, money
is not a continuously varying quantity, it comes in discrete units called
cents. Therefore use integers for money but count in cents (or pennies or
whatever).
 
C

Chris Whitworth

100% "John Harrison said:
PS using floating point values to represent money is a design error,
money is not a continuously varying quantity, it comes in discrete
units called cents. Therefore use integers for money but count in
cents (or pennies or whatever).

Banks frequently count fractions of a cent. See the film "Office Space" for
further details :)

Also, not everyone in the world uses US$ as their currency.

Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,175
Messages
2,570,947
Members
47,498
Latest member
yelene6679

Latest Threads

Top