0

When using std::to_string with a float that for example has the value 3.14f it yields in a string looking like this: 3.140000

Is it possible to prevent the generation of the unnecessary zeros in the back?

user11914177
  • 885
  • 11
  • 33
  • 1
    https://stackoverflow.com/questions/29200635/convert-float-to-string-with-precision-number-of-decimal-digits-specified – agent_bean Sep 17 '19 at 19:33
  • Define "zeroes". Do you want a fixed number of places, or to trim off the trailing zeroes? Internally the number is always represented with lots of zeroes. It's only when stringified that those show up. – tadman Sep 17 '19 at 19:34
  • 1
    Yes, but it's probably not what you want. Consider 3.13999999999999999999 (which is the same value) – Jeffrey Sep 17 '19 at 19:34
  • `std::to_string` does not give you this kind of control. If you want fine control over the conversion, see the duplicate for more elaborate solutions. – François Andrieux Sep 17 '19 at 19:35
  • @rafaelgonzalez Thanks for your awnser – user11914177 Sep 17 '19 at 19:35
  • @rafaelgonzalez This question is not of duplicate as it is not requesting rounding but removal of unnecessary trailing 0's which shortens the representation without reduction in precision. This is useful in serialization. A simple wrapper function to drop the trailing 0's would be appropriate. Further, where speed is important, `std::to_chars` in C++17 provides far faster conversion results and doesn't append unnecessary 0s. – doug Sep 17 '19 at 20:03
  • @doug You cannot look at trailing zeros without reducing precision in some cases. Base 2 numbers don't always have (finite) exact base 10 representation. Anyone who wants to remove trailing zero missed the point already. Rounding makes sense, though. So, the question is either duplicate or doesn't make complete sense. – Jeffrey Sep 17 '19 at 20:36
  • @rafaelgonzalez. Agreed that, even though there's lots of whole numbers as well as numbers like 2.5 or 7.375, most base2 (IEEE) floats don't have trailing zeros at max precision. But that wasn't the question. It was using `std::to_string` and getting rid of unnecessary trailing zeros. The duplicate is about precision and rounding and this question is about redundancy reduction with no change in the accuracy `std::to_string` provides. However, the OP's question wording aside, he appears to want to control the precision instead. – doug Sep 17 '19 at 21:11

0 Answers0