473,671 Members | 2,290 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A question: Convert double to string

hi

I need to do this (convert double to string) fast, safe and
portable. Is there any way to do this ?

Except the ways following:
1. C++ I/O stream, stringstream (and boost::lexical_ cast)
2. sprintf (and its brothers)
3. any nonstandard C/C++ functions

PS: if any implementation of i/o stream was faster than
sprintf, please tell me, thank you.

Sep 22 '07 #1
21 7490
Aman JIANG wrote:
hi

I need to do this (convert double to string) fast, safe and
portable. Is there any way to do this ?

Except the ways following:
1. C++ I/O stream, stringstream (and boost::lexical_ cast)
2. sprintf (and its brothers)
3. any nonstandard C/C++ functions
How is that supposed to be possible? You don't want any standard way of
doing it and you don't want any non-standard way of doing it. I guess that
limits the choices a bit.

Sep 22 '07 #2
On Sep 22, 3:11 pm, Rolf Magnus <ramag...@t-online.dewrote:
Aman JIANG wrote:
hi
I need to do this (convert double to string) fast, safe and
portable. Is there any way to do this ?
Except the ways following:
1. C++ I/O stream, stringstream (and boost::lexical_ cast)
2. sprintf (and its brothers)
3. any nonstandard C/C++ functions

How is that supposed to be possible? You don't want any standard way of
doing it and you don't want any non-standard way of doing it. I guess that
limits the choices a bit.
Thanks.

I suppose it is possible because i am asking a question. And I have
this
question because:
A. sprintf was hard to be safe
B. iostream was pretty slow, it's hard to believe it can be used on a
program what have lots and lots of operation, It has many unwanted
actions
just for a numerical value conversion.

So, i want to find a better way.
(sorry for my poor english)

Sep 22 '07 #3
"Aman JIANG" <Am*******@gmai l.comwrote in message
news:11******** **************@ k79g2000hse.goo glegroups.com.. .
: On Sep 22, 3:11 pm, Rolf Magnus <ramag...@t-online.dewrote:
: Aman JIANG wrote:
: hi
: >
: I need to do this (convert double to string) fast, safe and
: portable. Is there any way to do this ?
: >
: Except the ways following:
: 1. C++ I/O stream, stringstream (and boost::lexical_ cast)
: 2. sprintf (and its brothers)
: 3. any nonstandard C/C++ functions
: >
: How is that supposed to be possible? You don't want any standard
: way of doing it and you don't want any non-standard way of doing
: it. I guess that limits the choices a bit.
:
: Thanks.
:
: I suppose it is possible because i am asking a question.
: And I have this question because:
: A. sprintf was hard to be safe
It is. Safer variants of sprintf can help, as can writing
directly to a file. But ultimately, it might make sense
to check the range and validity of the converted number.

: B. iostream was pretty slow, it's hard to believe it can be used
: on a program what have lots and lots of operation, It has many
: unwanted actions just for a numerical value conversion.
The stringstream approach has its overheads, agreed, but is safe.

: So, i want to find a better way.
: (sorry for my poor english)
If iostream is too slow on your platform for your application, the
performance-sensitive way to go is the printf family of functions.
Because you might want to use some platform-specific extension
to make it safe, it could be a good idea to wrap it behind
your own function - using the buffer-allocation and format-
specification policy you want.
As to rewriting or adapt a dtoa function into your application,
I doubt it would be a sensible priority in terms of performance
optimization (there should be more important things to tune...)

hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com

Sep 22 '07 #4
PS: Third party library was expected.

Sep 22 '07 #5
On Sep 22, 4:59 pm, "Ivan Vecerina"
<_INVALID_use_w ebfo...@ivan.ve cerina.comwrote :
If iostream is too slow on your platform for your application, the
performance-sensitive way to go is the printf family of functions.
Because you might want to use some platform-specific extension
I don't want to use any 'platform-specific extension', it isn't cross-
platform code :( Otherwise maybe I can research the floating point
format on all platforms...
to make it safe, it could be a good idea to wrap it behind
your own function - using the buffer-allocation and format-
specification policy you want.
As to rewriting or adapt a dtoa function into your application,
I doubt it would be a sensible priority in terms of performance
optimization (there should be more important things to tune...)
It's hard. I have no idea to confirm the size of the buffer. for
double, it can be 316 bytes, on my platforms, and i don't know the
sizes on other platforms...

Sep 22 '07 #6
Aman JIANG wrote:
I need to do this (convert double to string) fast, safe and
portable. Is there any way to do this ?
You could roll your own printing code, something like this:

1. Test for NaN with x != x
2. Test for infinity by comparing with FLT_MAX (in <cfloat>)
3. Split into integer and fractional parts with modf (<cmath>)
4. Repeatedly div-mod the integer part to extract the digits
left of the decimal point, and repeatedly multiply and modf
the fractional part to get the digits to the right. It will
probably be faster to work in base 10^9 rather than 10.

-- Ben
Sep 22 '07 #7
I wrote:
2. Test for infinity by comparing with FLT_MAX (in <cfloat>)
Sorry, I meant DBL_MAX of course.

-- Ben
Sep 22 '07 #8
"Aman JIANG" <Am*******@gmai l.comwrote in message
news:11******** **************@ y42g2000hsy.goo glegroups.com.. .
: On Sep 22, 4:59 pm, "Ivan Vecerina"
: <_INVALID_use_w ebfo...@ivan.ve cerina.comwrote :
: If iostream is too slow on your platform for your application, the
: performance-sensitive way to go is the printf family of functions.
: Because you might want to use some platform-specific extension
:
: I don't want to use any 'platform-specific extension', it isn't cross-
: platform code :( Otherwise maybe I can research the floating point
: format on all platforms...
:
: to make it safe, it could be a good idea to wrap it behind
: your own function - using the buffer-allocation and format-
: specification policy you want.
: As to rewriting or adapt a dtoa function into your application,
: I doubt it would be a sensible priority in terms of performance
: optimization (there should be more important things to tune...)
:
: It's hard. I have no idea to confirm the size of the buffer. for
: double, it can be 316 bytes, on my platforms, and i don't know the
: sizes on other platforms...

If you want a more precise answer than what you've obtained so far,
you need to also say more about what you want:
- what allocation strategy would you like to rely on for the
returned character buffer?
- what output formats do you want to support?
I personally use a wrapper over platform-specific variants
of sprintf, which returns the result as an std::string
(using a stack buffer for the initial output if possible, and
a dynamically allocated buffer for larger outputs - relying
e.g. on _vscprintf do determine buffer size).
But if I am writing to a file, fprintf does the job well.

If you really want a custom solution, you should be able to find
some open source implementation to start from... look
for dtoa() or fcvt() as common low-level function names.
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <http://www.brainbench.com

Sep 22 '07 #9
Aman JIANG wrote:
On Sep 22, 4:59 pm, "Ivan Vecerina"
<_INVALID_use_w ebfo...@ivan.ve cerina.comwrote :
>If iostream is too slow on your platform for your application, the
performance-sensitive way to go is the printf family of functions.
Because you might want to use some platform-specific extension

I don't want to use any 'platform-specific extension', it isn't cross-
platform code :( Otherwise maybe I can research the floating point
format on all platforms...
>to make it safe, it could be a good idea to wrap it behind
your own function - using the buffer-allocation and format-
specificatio n policy you want.
As to rewriting or adapt a dtoa function into your application,
I doubt it would be a sensible priority in terms of performance
optimization (there should be more important things to tune...)

It's hard. I have no idea to confirm the size of the buffer. for
double, it can be 316 bytes, on my platforms, and i don't know the
sizes on other platforms...
Do you have any platform independent method (however involved) to compute an
upper bound for the length of the buffer at runtime? If so, you could use a
trick like the following:

#include <string>
#include <cassert>

template < unsigned N >
struct buffer_length {

static unsigned const value = 1 + buffer_length<N-1>::value * 2;

};

template <>
struct buffer_length<1 {

static unsigned const value = 1;

};

template <>
struct buffer_length<0 {

static unsigned const value = 1;

};

template < unsigned N >
std::string function_needin g_a_buffer ( double d ) {
char buffer [ buffer_length<N >::value ];
// do something
buffer[0] = 'c';
buffer[1] = 0;
return ( std::string( buffer ) );
}
typedef std::string(* function_ptr )( double );

function_ptr get_function ( unsigned needed_size ) {
unsigned N = 0;
while ( needed_size != 0 ) {
++N;
needed_size /= 2;
}
switch ( N ) {
case 0 : { return &function_needi ng_a_buffer<0>; }
case 1 : { return &function_needi ng_a_buffer<1>; }
case 2 : { return &function_needi ng_a_buffer<2>; }
case 3 : { return &function_needi ng_a_buffer<3>; }
case 4 : { return &function_needi ng_a_buffer<4>; }
case 5 : { return &function_needi ng_a_buffer<5>; }
case 6 : { return &function_needi ng_a_buffer<6>; }
case 7 : { return &function_needi ng_a_buffer<7>; }
case 8 : { return &function_needi ng_a_buffer<8>; }
case 9 : { return &function_needi ng_a_buffer<9>; }
case 10 : { return &function_needi ng_a_buffer<10> ; }
// ...
}
assert( false );
}

std::string true_function ( double d ) {
static function_ptr the_ptr = get_function( 325 );
// in real life, use some magic to determine the needed
// buffer size
return ( the_ptr(d) );
}

#include <iostream>

int main ( void ) {
std::cout << true_function( 1 ) << '\n';
}
Note that this executes the code to select the right buffer size only once
and not every time a double is converted.
Since speed seems to be of the essence in your application, using the
sprintf family is probably the way to go. It is usually heavily optimized
and should be almost impossible to beat. I would concentrate on writing a
wrapper around it that makes it safe and convenient to use without
compromising efficiency.
Best

Kai-Uwe Bux

Sep 22 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
47064
by: cindy liu | last post by:
Hi, In .Net, how to convert a string to a double? Thanks in advance! Cindy
2
1291
by: Sam | last post by:
Hi, I have a winform app where users enters in data. The data is comprised of options (strings), values (doubles) and so on. I am trying to pass this data to a class which will be used as a container class. How do I pass values (double) that are entered in textboxes since they are text? Should I use System.Convert? Or should I save the data as strings and then when the data is needed convert to double using System.Convert? Thanks
2
4958
by: Pascal | last post by:
Why does this not work, and how should i do this convert in stead: string x = double.MinValue.ToString(); double y = Convert.ToDouble(x); i get this exception: An unhandled exception of type 'System.OverflowException' occurred in mscorlib.dll Additional information: Value was either too large or too small for a Double. Pascal
2
11508
by: paul gao via .NET 247 | last post by:
hi all. In my program I need to convert a double number to stringrepresentation in fraction format and vise versa. For example,convert 0.75 to string "3/4" and convert string "1/2" to 0.5.The class will only need to handle numbers that increment by1/32. That is 1/32, 2/32, 3/32.... 31/32, 1. If the doublenumber is 0.28 which is between 1/4 and 9/32, the string shouldbe 9/32(go with the bigger number). TIA --------------------------------...
5
3016
by: John Baro | last post by:
I have a richtextbox which I want the "literal" rtf of. richtextbox.rtf returns {\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033\\uc1 }\r\n\0 when i put this into a string I get "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033\\uc1 }\r\n\0" I want this to be @"{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033\\uc1 }\r\n\0" to treat the escape characters as literals
17
4361
by: David Scemama | last post by:
Hi, I'm writing a program using VB.NET that needs to communicate with a DOS Pascal program than cannot be modified. The communication channel is through some file databases, and I have a huge problem writing VB Double values to the file so as the Pascal program can read them as Pascal Real values. I've managed to find the algorithm to read the Pascal Real format and convert it to a VB Double, but I cannot figure out the opposite...
3
1529
by: Ken H | last post by:
Hi I have a question about architecting solutions.. I have a part of a project which requires me to track person details (name, addresses, etc... Should I be creating Person objects, Address objects etc as Business layer classes and then have an data access layer which actually save / updates / delete to and from the DB.. If so, and bearing in mind the 'easiest' way to pass data between the layers would be with a dataset - should my BL...
4
4514
by: Edwin Knoppert | last post by:
In my code i use the text from a textbox and convert it to a double value. I was using Convert.ToDouble() but i'm used to convert comma to dot. This way i can assure the text is correct. However it seems this convert is determined by the local settings and comma is indeed used as decimal separator. Is there another way to convert a dotted value to a double variable? Like 1234.5 and not 1234,5
5
3198
by: tjay | last post by:
Hi. I wrote some code using sprintf and atof to store a double as a string of fixed length and to convert it back to a double variable. The string is stored in a char buffer global variable. I'm afraid it might contain bugs though. If I serialize a double, I get a string of the format "-1.0000000000000000e+212". This string gets stored in the buffer. Then, to convert it back into a double, I pass it to the atof function. The problem...
5
1623
by: Bartholomew Simpson | last post by:
Slightly OT, but someone may know an algorithm to help me do this .... I have six numbers that I want to encode into one single larger number. The 6 numbers may be presented as ff: number Range num1 num2
0
8390
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8911
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8819
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8597
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8667
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5692
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4222
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4402
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2048
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.