- A Course By Curiosity
- stringstream
- to_string()
- sprintf()
- Custom Implementation
- Conclusion
- Thread: C++ double to string drops final zeroes
- C++ double to string drops final zeroes
- Re: C++ double to string drops final zeroes
- Re: C++ double to string drops final zeroes
- Re: C++ double to string drops final zeroes
- Bookmarks
- Posting Permissions
- Convert a double to a QString
- 5 Answers 5
- std::to_string (3) - Linux Manuals
- Parameters
- Return value
- Exceptions
- Notes
A Course By Curiosity
Converting numbers to string is a frequent operation when we have to transmit data as a character string to any system. In ultra low latency systems this conversion can contribute to almost 20% of the system latency, when the precision requirement is higher.
Let us consider the popular ways of converting double to string in C++.
stringstream
std::stringstream provides a simple and easy way of converting double to string.
Here is a code snippet.
std::stringstream strval; double dval = 1729.314; strvalto_string()
double dval = 1729.314; const char* finalValue = std::to_string(dval).to_string()sprintf()
char finalValue[1024]; double dval = 1729.314; sprintf(finalValue, "%f", dval);Which one do you prefer in a latency sensitive project?
Let us analyze the performance of each of the above methods.
But buffer we proceed, let us think of a custom way of doing it on our own for better performance.Custom Implementation
Integer to string conversion can be cached if we know the range of integers we are going to use. For example, we can cache a millon integers which could cost hardly 10 MB.
We can cut double precision numbers to two integers, numbers before and after the decimal separator. Then its a matter of converting these integers and concatenating both with decimal separator.
The only edge case we need to handle here is when the number after decimal separator has leading 0s, like 1.02.
One idea is to multiply the number after decimal separator with power of 10 (better to take 10^maximum precision). If the number of digits is less than the power of 10(maximum precision), then we have to prepend the number with 0s.Lets now see the performance comparison of all the above approaches:
The above benchmark is done by executing the same example using all the 4 approaches discussed before.
Benchmark is done on converting random double precision numbers of 4 digits decimal precision, 1000 times.From the above graph you can see that stringstream is the worst. Median latency for stringstream is ~5.8 micro seconds.
stod() is the next better, which is ~4.2 micro seconds.
sprintf() provides event better, which is ~3 micro seconds. So the powerful C function beats its C++ counter parts.
Finally our custom implementation outperforms all the standard functions by miles. Its median latency is ~500 nano seconds which is more than 6 times better than sprintf!!Conclusion
For ultra low latency applications its better to have handcrafted functions for double conversion.
Standard library functions is not fast enough especially if the decimal precision required is more.
Custom implementation can gain lot of advantage depending on the use case. For eg: in our case we have used more memory for gaining on reducing latency. Its a better bet if you have enough RAM and has more stricter latency requirements.Thread: C++ double to string drops final zeroes
5 Cups of Ubuntu
C++ double to string drops final zeroes
I'm trying to convert doubles to strings in order to dynamically generate new filenames. My code works well except that my conversion function drops the trailing 0's from my doubles. For example, 3.0 becomes 3 after being converted to a string. I would like to keep the 0's.
string dtos ( double dbl )
<
ostringstream strs ;
strs string str = strs . str ();Thanks for your help! I'd be grateful even if you just point me to the right resource to read. Unfortunately, I've hit the limit of my patience today for searching through unhelpful documentation :-/
I Ubuntu, Therefore, I Am
Re: C++ double to string drops final zeroes
#include sstream ss; double d = 3.0; ssI don't recall of a quick method to just get a single zero with a higher precision setting. You'll probably have to parse the string for that.
5 Cups of Ubuntu
Re: C++ double to string drops final zeroes
Hi MadCow108, thanks for the quick reply! I haven't had time to test it yet, but I'll let you know if it worked as soon as I do.5 Cups of Ubuntu
Re: C++ double to string drops final zeroes
Great, that totally worked. I want all the numbers to be of equal length, so different numbers of 0's isn't a problem. Here is my new code:string dtos ( double dbl )
<
ostringstream strs ;
strs string str = strs . str ();
- Site Areas
- Settings
- Private Messages
- Subscriptions
- Who's Online
- Search Forums
- Forums Home
- Forums
- The Ubuntu Forum Community
- Ubuntu Official Flavours Support
- New to Ubuntu
- General Help
- Installation & Upgrades
- Hardware
- Desktop Environments
- Networking & Wireless
- Multimedia Software
- Ubuntu Specialised Support
- Ubuntu Development Version
- Security
- Virtualisation
- Ubuntu Servers, Cloud and Juju
- Server Platforms
- Ubuntu Cloud and Juju
- Gaming & Leisure
- Emulators
- Wine
- Development & Programming
- Packaging and Compiling Programs
- Development CD/DVD Image Testing
- Ubuntu Application Development
- Ubuntu Dev Link Forum
- Programming Talk
- Repositories & Backports
- Ubuntu Backports
- Bug Reports / Support
- Ubuntu Backports
- System76 Support
- Apple Hardware Users
- Ubuntu Community Discussions
- Ubuntu, Linux and OS Chat
- Recurring Discussions
- Full Circle Magazine
- The Cafe
- Cafe Games
- Market
- Mobile Technology Discussions (CLOSED)
- Announcements & News
- Weekly Newsletter
- Membership Applications
- The Fridge Discussions
- Forum Council Agenda
- Forum Feedback & Help
- Request a LoCo forum
- Resolution Centre
- Ubuntu, Linux and OS Chat
- Other Discussion and Support
- Other OS Support and Projects
- Other Operating Systems
- Ubuntu/Debian BASED
- Debian
- MINT
- Arch and derivatives
- Fedora/RedHat and derivatives
- Mandriva/Mageia
- Slackware and derivatives
- openSUSE and SUSE Linux Enterprise
- Mac OSX
- PCLinuxOS
- Gentoo and derivatives
- Windows
- BSD
- Any Other OS
- Other Operating Systems
- Assistive Technology & Accessibility
- Art & Design
- Education & Science
- Documentation and Community Wiki Discussions
- Tutorials
- Outdated Tutorials & Tips
- Ubuntu Women
- Ubuntu LoCo Team Forums
- Americas LoCo Teams
- Argentina Team
- Software
- Hardware
- Comunidad
- Arizona Team - US
- Arkansas Team - US
- Brazil Team
- California Team - US
- Canada Team
- Centroamerica Team
- Chile Team
- Comunidad
- Hardware
- Software
- Instalaci�n y Actualizaci�n
- Colombia Team - Colombia
- Georgia Team - US
- Illinois Team
- Indiana - US
- Kentucky Team - US
- Maine Team - US
- Minnesota Team - US
- Mississippi Team - US
- Nebraska Team - US
- New Mexico Team - US
- New York - US
- North Carolina Team - US
- Ohio Team - US
- Oklahoma Team - US
- Oregon Team - US
- Pennsylvania Team - US
- Peru Team
- Texas Team - US
- Uruguay Team
- Utah Team - US
- Virginia Team - US
- West Virginia Team - US
- Argentina Team
- Asia and Oceania LoCo Teams
- Australia Team
- Bangladesh Team
- Hong Kong Team
- Myanmar Team
- Philippine Team
- Singapore Team
- Europe, Middle East, and African (EMEA) LoCo Teams
- Albania Team
- Catalan Team
- Portugal Team
- Egypt Team
- Georgia Team
- Ireland Team - Ireland
- Kenyan Team - Kenya
- Kurdish Team - Kurdistan
- Lebanon Team
- Morocco Team
- Saudi Arabia Team
- Sudan Team
- Tunisia Team
- Other Forums & Teams
- LoCo Archive
- Afghanistan Team
- Alabama Team - US
- Alaska Team - US
- Algerian Team
- Andhra Pradesh Team - India
- Austria Team
- Bangalore Team
- Bolivia Team
- Cameroon Team
- Colorado Team - US
- Connecticut Team
- Costa Rica Team
- Delhi Team
- Ecuador Team
- El Salvador Team
- Florida Team - US
- Galician LoCo Team
- Greek team
- Hawaii Team - US
- Honduras Team
- Idaho Team - US
- Iowa Team - US
- Jordan Team
- Kansas Team - US
- Libya Team
- Louisiana Team - US
- Maryland Team - US
- Massachusetts Team
- Michigan Team - US
- Missouri Team - US
- Montana Team - US
- Namibia Team
- Nevada Team - US
- New Hampshire Team - US
- New Jersey Team - US
- Northeastern Team - US
- Panama Team
- Paraguay Team
- Qatar Team
- Quebec Team
- Rhode Island Team - US
- Senegal Team
- South Carolina Team - US
- South Dakota Team - US
- Switzerland Team
- Tamil Team - India
- Tennessee Team - US
- Trinidad & Tobago Team
- Uganda Team
- United Kingdom Team
- US LoCo Teams
- Venezuela Team
- Wales Team
- Washington DC Team - US
- Washington State Team - US
- Wisconsin Team
- Yemen Team
- Za Team - South Africa
- Zimbabwe Team
- Americas LoCo Teams
- Other OS Support and Projects
- Ubuntu Official Flavours Support
Bookmarks
Bookmarks
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Convert a double to a QString
@Macmade, I am new to QT and CPP. But i have a java code so i want to convert into cpp for qt application.
5 Answers 5
Use QString's number method (docs are here):
double valueAsDouble = 1.2; QString valueAsString = QString::number(valueAsDouble);
CAUTION: That call may lead to loss of precision. I did that same call once and I got 6.84442e+06 from 6844418.0, for example. They were metric UTM coordinates, so that 10m loss was unacceptable. Please, do be careful depending on the application. I used std::stringstream ss; ss << std::setprecision( 12 ); ss << (double)value; How do I markdown code blocks in this thing? <>
Note: For the 'g' and 'G' formats, the precision represents the maximum number of significant digits (trailing zeroes are omitted). For example 1.0 will be converted to "1"
Instead of QString::number() i would use QLocale::toString() , so i can get locale aware group seperatores like german "1.234.567,89".
Building on @Kristian's answer, I had a desire to display a fixed number of decimal places. That can be accomplished with other arguments in the QString::number(. ) function. For instance, I wanted 3 decimal places:
double value = 34.0495834; QString strValue = QString::number(value, 'f', 3); // strValue == "34.050"
The 'f' specifies decimal format notation (more info here, you can also specify scientific notation) and the 3 specifies the precision (number of decimal places). Probably already linked in other answers, but more info about the QString::number function can be found here in the QString documentation
std::to_string (3) - Linux Manuals
Defined in header
std::string to_string( int value ); (1) (since C++11)
std::string to_string( long value ); (2) (since C++11)
std::string to_string( long long value ); (3) (since C++11)
std::string to_string( unsigned value ); (4) (since C++11)
std::string to_string( unsigned long value ); (5) (since C++11)
std::string to_string( unsigned long long value ); (6) (since C++11)
std::string to_string( float value ); (7) (since C++11)
std::string to_string( double value ); (8) (since C++11)
std::string to_string( long double value ); (9) (since C++11)
Converts a numeric value to std::string.
1) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%d", value) would produce for sufficiently large buf.
2) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%ld", value) would produce for sufficiently large buf.
3) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%lld", value) would produce for sufficiently large buf.
4) Converts an unsigned decimal integer to a string with the same content as what std::sprintf(buf, "%u", value) would produce for sufficiently large buf.
5) Converts an unsigned decimal integer to a string with the same content as what std::sprintf(buf, "%lu", value) would produce for sufficiently large buf.
6) Converts an unsigned decimal integer to a string with the same content as what std::sprintf(buf, "%llu", value) would produce for sufficiently large buf.
7,8) Converts a floating point value to a string with the same content as what std::sprintf(buf, "%f", value) would produce for sufficiently large buf.
9) Converts a floating point value to a string with the same content as what std::sprintf(buf, "%Lf", value) would produce for sufficiently large buf.
Parameters
value - a numeric value to convert
Return value
a string holding the converted value
Exceptions
May throw std::bad_alloc from the std::string constructor.
Notes
* With floating point types std::to_string may yield unexpected results as the number of significant digits in the returned string can be zero, see the example.
* The return value may differ significantly from what std::cout prints by default, see the example.
* std::to_string relies on the current locale for formatting purposes, and therefore concurrent calls to std::to_string from multiple threads may result in partial serialization of calls. C++17 provides std::to_chars as a higher-performance locale-independent alternative.