+ 1

What's wrong with to_string

Hi Am i missing something here in below code? I am always getting value truncated due to to_string. What to do to get exact value from double to string in to_string? https://sololearn.com/compiler-playground/crQgPYAU0HfZ/?ref=app

19th Sep 2024, 12:44 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 Réponses
+ 2
Ketan Lalcheta if it is important to echo back the user float value exactly as entered, then it might work better to receive the entry as a string. Convert the string to float or double or long double for calculation purposes. Use the string for display. (Then you can count characters up to the decimal in order to determine the input precision).
19th Sep 2024, 4:34 PM
Brian
Brian - avatar
+ 2
I looked it up and learned that to_string() has a fixed limit of 6 decimal places. You cannot adjust it. You can use stringstream with iomanip and filter the value through setprecision().
19th Sep 2024, 1:23 PM
Brian
Brian - avatar
+ 2
Floating point precision is always an issue with programming. This particular function, to_string(), is actually documented that it may have precision issues, which you've discovered. In practice, most programs do not need that level of precision. If they did not have restrictions on precision, then you would see a lot of numbers like 1.000000000000001 showing up. There is a newer command, std::format() which can be used to specify precision, but that doesn't work on the SoloLearn compiler. Apparently SoloLearn is using an older standard library for C++. You can read about it here: https://en.cppreference.com/w/cpp/utility/format/spec
19th Sep 2024, 1:24 PM
Jerry Hobby
Jerry Hobby - avatar
+ 1
Jerry Hobby thanks but unfortunately our standard tool is still Visual Studio 2019 and cannot upgrade it for this issue
19th Sep 2024, 1:27 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Brian I also used set precision when I was supposed to use truncated value. Fixed and set precision is used by me . I observed this issue when it was not supposed to have any precision and should show user entered value. In that case , I was using to_string. Now if I want to use also, what should be the precision value to set as I don't know what user has entered
19th Sep 2024, 1:29 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Sounds good Brian
19th Sep 2024, 6:12 PM
Ketan Lalcheta
Ketan Lalcheta - avatar