Linux double to string

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; strval

to_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

jondiced is offline5 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 :-/

MadCow108 is offlineI Ubuntu, Therefore, I Am

Re: C++ double to string drops final zeroes

#include sstream ss; double d = 3.0; ss 

I 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.

jondiced is offline5 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.

jondiced is offline5 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
    1. Ubuntu Official Flavours Support
      1. New to Ubuntu
      2. General Help
      3. Installation & Upgrades
      4. Hardware
      5. Desktop Environments
      6. Networking & Wireless
      7. Multimedia Software
    2. Ubuntu Specialised Support
      1. Ubuntu Development Version
      2. Security
      3. Virtualisation
      4. Ubuntu Servers, Cloud and Juju
        1. Server Platforms
        2. Ubuntu Cloud and Juju
      5. Gaming & Leisure
        1. Emulators
      6. Wine
      7. Development & Programming
        1. Packaging and Compiling Programs
        2. Development CD/DVD Image Testing
        3. Ubuntu Application Development
        4. Ubuntu Dev Link Forum
        5. Programming Talk
        6. Repositories & Backports
          1. Ubuntu Backports
            1. Bug Reports / Support
      8. System76 Support
      9. Apple Hardware Users
    3. Ubuntu Community Discussions
      1. Ubuntu, Linux and OS Chat
        1. Recurring Discussions
        2. Full Circle Magazine
      2. The Cafe
        1. Cafe Games
      3. Market
      4. Mobile Technology Discussions (CLOSED)
      5. Announcements & News
      6. Weekly Newsletter
      7. Membership Applications
      8. The Fridge Discussions
      9. Forum Council Agenda
      10. Forum Feedback & Help
        1. Request a LoCo forum
      11. Resolution Centre
    4. Other Discussion and Support
      1. Other OS Support and Projects
        1. Other Operating Systems
          1. Ubuntu/Debian BASED
          2. Debian
          3. MINT
          4. Arch and derivatives
          5. Fedora/RedHat and derivatives
          6. Mandriva/Mageia
          7. Slackware and derivatives
          8. openSUSE and SUSE Linux Enterprise
          9. Mac OSX
          10. PCLinuxOS
          11. Gentoo and derivatives
          12. Windows
          13. BSD
          14. Any Other OS
      2. Assistive Technology & Accessibility
      3. Art & Design
      4. Education & Science
      5. Documentation and Community Wiki Discussions
      6. Tutorials
        1. Outdated Tutorials & Tips
      7. Ubuntu Women
      8. Ubuntu LoCo Team Forums
        1. Americas LoCo Teams
          1. Argentina Team
            1. Software
            2. Hardware
            3. Comunidad
          2. Arizona Team - US
          3. Arkansas Team - US
          4. Brazil Team
          5. California Team - US
          6. Canada Team
          7. Centroamerica Team
          8. Chile Team
            1. Comunidad
            2. Hardware
            3. Software
            4. Instalaci�n y Actualizaci�n
          9. Colombia Team - Colombia
          10. Georgia Team - US
          11. Illinois Team
          12. Indiana - US
          13. Kentucky Team - US
          14. Maine Team - US
          15. Minnesota Team - US
          16. Mississippi Team - US
          17. Nebraska Team - US
          18. New Mexico Team - US
          19. New York - US
          20. North Carolina Team - US
          21. Ohio Team - US
          22. Oklahoma Team - US
          23. Oregon Team - US
          24. Pennsylvania Team - US
          25. Peru Team
          26. Texas Team - US
          27. Uruguay Team
          28. Utah Team - US
          29. Virginia Team - US
          30. West Virginia Team - US
        2. Asia and Oceania LoCo Teams
          1. Australia Team
          2. Bangladesh Team
          3. Hong Kong Team
          4. Myanmar Team
          5. Philippine Team
          6. Singapore Team
        3. Europe, Middle East, and African (EMEA) LoCo Teams
          1. Albania Team
          2. Catalan Team
          3. Portugal Team
          4. Egypt Team
          5. Georgia Team
          6. Ireland Team - Ireland
          7. Kenyan Team - Kenya
          8. Kurdish Team - Kurdistan
          9. Lebanon Team
          10. Morocco Team
          11. Saudi Arabia Team
          12. Sudan Team
          13. Tunisia Team
        4. Other Forums & Teams
        5. LoCo Archive
          1. Afghanistan Team
          2. Alabama Team - US
          3. Alaska Team - US
          4. Algerian Team
          5. Andhra Pradesh Team - India
          6. Austria Team
          7. Bangalore Team
          8. Bolivia Team
          9. Cameroon Team
          10. Colorado Team - US
          11. Connecticut Team
          12. Costa Rica Team
          13. Delhi Team
          14. Ecuador Team
          15. El Salvador Team
          16. Florida Team - US
          17. Galician LoCo Team
          18. Greek team
          19. Hawaii Team - US
          20. Honduras Team
          21. Idaho Team - US
          22. Iowa Team - US
          23. Jordan Team
          24. Kansas Team - US
          25. Libya Team
          26. Louisiana Team - US
          27. Maryland Team - US
          28. Massachusetts Team
          29. Michigan Team - US
          30. Missouri Team - US
          31. Montana Team - US
          32. Namibia Team
          33. Nevada Team - US
          34. New Hampshire Team - US
          35. New Jersey Team - US
          36. Northeastern Team - US
          37. Panama Team
          38. Paraguay Team
          39. Qatar Team
          40. Quebec Team
          41. Rhode Island Team - US
          42. Senegal Team
          43. South Carolina Team - US
          44. South Dakota Team - US
          45. Switzerland Team
          46. Tamil Team - India
          47. Tennessee Team - US
          48. Trinidad & Tobago Team
          49. Uganda Team
          50. United Kingdom Team
          51. US LoCo Teams
          52. Venezuela Team
          53. Wales Team
          54. Washington DC Team - US
          55. Washington State Team - US
          56. Wisconsin Team
          57. Yemen Team
          58. Za Team - South Africa
          59. Zimbabwe Team

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.

Источник

Читайте также:  Linux which files open by process
Оцените статью
Adblock
detector