Opened 11 years ago

Closed 11 years ago

#5796 closed Bugs (wontfix)

Casting from float to string using "lexical_cast<string>" gives inaccurate values.

Reported by: Mikko Partonen <mikkopartonen@…> Owned by: nasonov
Milestone: To Be Determined Component: lexical_cast
Version: Boost 1.47.0 Severity: Cosmetic
Keywords: lexical_cast, float Cc: antoshkka@…

Description

When casting floats to strings with lexical_cast<string>() for use in wxTextCtrl, the new boost versions adds a lot of nines or zeroes along with some random numbers at the end of the float values. For example, with an older boost version, I get "0.96" and "0.8" and with new versions, I get "0.959999979" and "0.800000012".

I believe this new feature has to do with this problem:

"The previous version of lexical_cast used the default stream precision for reading and writing floating-point numbers. For numerics that have a corresponding specialization of std::numeric_limits, the current version now chooses a precision to match."

This can easily be fixed by using an older version of lexical_cast.hpp file. Wouldn't it be better to fix this issue, so that I wouldn't need to use the old version of lexical_cast.hpp?

I attached the lexical_cast.hpp version with which conversions from floats to strings works.

Attachments (1)

lexical_cast.hpp (7.1 KB ) - added by Mikko Partonen <mikkopartonen@…> 11 years ago.
Working lexical_cast.hpp file.

Download all attachments as: .zip

Change History (3)

by Mikko Partonen <mikkopartonen@…>, 11 years ago

Attachment: lexical_cast.hpp added

Working lexical_cast.hpp file.

in reply to:  description comment:1 by Antony Polukhin, 11 years ago

Replying to Mikko Partonen <mikkopartonen@…>:

When casting floats to strings with lexical_cast<string>() for use in wxTextCtrl, the new boost versions adds a lot of nines or zeroes along with some random numbers at the end of the float values. For example, with an older boost version, I get "0.96" and "0.8" and with new versions, I get "0.959999979" and "0.800000012".

It is not a random number, it is the exact representation of float number: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16

This can easily be fixed by using an older version of lexical_cast.hpp file. Wouldn't it be better to fix this issue, so that I wouldn't need to use the old version of lexical_cast.hpp?

Think about all the people, who used an updated version of this library (years passed since 2005, so there will be plenty of them). They relay on current behavior, and such changes will break their code.

Current behavior was chosen because more people wanted to see precise numbers. When you convert number "1.000000099" in most cases you would like to see number "1.000000099" in output, not "1".

You can always use std::stringstream to convert numbers with specified precision.

comment:2 by Antony Polukhin, 11 years ago

Cc: antoshkka@… added
Resolution: wontfix
Status: newclosed
Note: See TracTickets for help on using tickets.