Skip to main content
gamedev.net
🔒 Locked

Converting a float to a string

Started by Shannon Barber 21 replies 1.4k views
Original Post
Shannon Barber
Shannon Barber
Does anyone know a function to convert a float to a string other than printf/sprintf? (any chance there''s an op code?)
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Void
Void
lexical_cast from www.boost.org
gmcbay
gmcbay
There''s no op code. Standard processors don''t even have a native ''string'' type. The most portable way to do it in C/C++ is to use sprintf. In C++, depending on the libraries available to you, you can do fancy casting, or use stringstreams to convert floats into C++ string types...But generally these methods are no faster than sprintf and could be quite a bit slower, depending upon implementation details.
GoofProg
GoofProg
Yes! Use the _fcvt function.
The nightmare travels across the cosmos with his burning mane.  The trail of ash that is produced. ?Have a nice day!?
MindWipe
MindWipe
Make you''re own function. It can''t be that hard

first you''ll multiply with enough to make it an integer (xxxx.000000)

And then just divide with one big value and (int) that and then and then you''ll just do a little ''if'' of ''switch'' and you''ll get one chat and continue doing that. It''s not that hard.


ie.

you have 23.51

first you *100 = 2351

then you do 2351/1000 and you''ll have 2.351 and you do (int) and you have 2 and then if (value == 2) DaChar[0]=''2'';
and then just do 2351-value*1000=351/100=3.51 and (int) = 3
do a if (or switch would be easier) and you''ll have DaChar[1]=''3''

no probelmo there. Do a while and you''ll get the function short and easy.

Don''t only rely on premade fuction. Allways thing a little, because there is allways someway you could do something in your own way.

/MindWipe




"If it doesn''t fit, force it; if it breaks, it needed replacement anyway."
"To some its a six-pack, to me it's a support group."
MatrixCubed
MatrixCubed
From VC++ Help (hope this comes out ok...)

_ecvt
Converts a double number to a string.

char *_ecvt( double value, int count, int *dec, int *sign );

Function Required Header Compatibility
_ecvt Win 95, Win NT


For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version


Return Value

_ecvt returns a pointer to the string of digits. There is no error return.

Parameters

value

Number to be converted

count

Number of digits stored

dec

Stored decimal-point position

sign

Sign of converted number

Remarks

The _ecvt function converts a floating-point number to a character string. The value parameter is the floating-point number to be converted. This function stores up to count digits of value as a string and appends a null character (''\0''). If the number of digits in value exceeds count, the low-order digit is rounded. If there are fewer than count digits, the string is padded with zeros.

Only digits are stored in the string. The position of the decimal point and the sign of value can be obtained from dec and sign after the call. The dec parameter points to an integer value giving the position of the decimal point with respect to the beginning of the string. A 0 or negative integer value indicates that the decimal point lies to the left of the first digit. The sign parameter points to an integer that indicates the sign of the converted number. If the integer value is 0, the number is positive. Otherwise, the number is negative.

_ecvt and _fcvt use a single statically allocated buffer for the conversion. Each call to one of these routines destroys the result of the previous call.

Example

/* ECVT.C: This program uses _ecvt to convert a
* floating-point number to a character string.
*/

#include
#include

void main( void )
{
int decimal, sign;
char *buffer;
int precision = 10;
double source = 3.1415926535;

buffer = _ecvt( source, precision, &decimal, &sign );
printf( "source: %2.10f buffer: ''%s'' decimal: %d sign: %d\n",
source, buffer, decimal, sign );
}


Output

source: 3.1415926535 buffer: ''3141592654'' decimal: 1 sign: 0


Data Conversion Routines | Floating-Point Support Routines

See Also atof, _fcvt, _gcvt



MatrixCubed
http://MatrixCubed.cjb.net






thuned
thuned
how about this?
find out how many decimal places you need (n), multiply the float by 10^n to get make it into an int.
use itoa.
then create a buffer w/ strlen(string) +1, strcpy the first part, add a ''.'' then strcpy the remaining decimal portion.
life is unfair, take advantage of it.UNMB2 - if the link doesn't work, try clicking it :)
jenova
jenova
you cannot just check for a ".", because floating point also could be scientific notation, could contain "e" for exponent. ANSI C function "atof" will do the job.

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
jenova
jenova
you cannot just check for a ".", because floating point also could be scientific notation, could contain "e" for exponent.

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
Shannon Barber
Shannon Barber
I want to convert a float to an ansi string, without using the C runtime, I started writing my own, but thought I'd check to see if there was one out there...

And the intel processors have instructions to work with null terminated strings, btw.

Edited by - Magmai Kai Holmlor on December 28, 2001 8:27:37 AM
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
ANSI2000
ANSI2000
Yeah there a few function to convert numbers(ints, floats) to strings and vise versa... It is part the standard c runtime like you said magmai.... I know of atoi() atof() look for those on the msdn help of vc++ and it will give you all the functions...
Shannon Barber
Shannon Barber
I wanted an ftoa _WITHOUT_ using the C run-time

Well, this is what I put together, it's crude&ugly:
      
union Float
{
float f;
struct
{
unsigned int mantissa:23;
unsigned int exponent:8;
unsigned int sign:1;
};
};

void ftoa(char* s, float f_, int decimals=4)
{
Float f;
f.f = f_;
int exp = unsigned char(f.exponent + 128);
int man = 0x00800000 | f.mantissa;

unsigned char pbcd[10];
unsigned char bcd[18];

if(0xff==f.exponent)
{//Special Case

if(f.mantissa)
{//Not A Number

if(f.mantissa&0x00400000)
*s = 'Q';//Undefined Result

else
*s= 'S';//Invalid Operand/Operation

s++;
strcpy(s, "NaN");
return;
}
else
{//Infinity

if(f.sign)
{
*s = '-';
s++;
}
strcpy(s, "Inf");
return;
}
}

if(!f.exponent)
{
if(!f.mantissa)
{//Zero is Special

if(f.sign)
{
*s = '-';
s++;
}
*s = '0';
++s;
*s = '.';
++s;
for(int i=0; i<decimals; ++i)
s[i] = '0';
return;
}
else
{//Denormalize

man &= 0x007fffff;
}
}

if(f.sign)
{
*s = '-';
s++;
}

//Calculate scaling factor as dictated by the desired decimal output

int scale=1;
for(int i=0; i<decimals; ++i)
scale*=10;

//Convert float into packed BCD

//scale by factor (neccessary to extract decimal digits)

#pragma warning(disable:4409)
__asm
{
fld f_
fimul scale
fbstp [pbcd]
}

//Unpack BCD

unsigned char* d=&bcd[0];
unsigned char* p=&pbcd[0];
for(;p<&pbcd[10]; ++p)
{
*d = *p;
*d &= 0x0F;
++d;
*d = *p;
*d >>= 4;
++d;
}

//Convert BCD to string

//skip leading zeros before the decimal point

//_but print at least a 0 before it (+1)

for(d=&bcd[18]; d>=&bcd[decimals+1]; --d)
{
if(*d!=0)
break;
}
//digits before the decimal

for(; d>=&bcd[decimals]; --d)
{
*s = *d + '0';
s++;
}
*s = '.';
++s;
//digits after the decimal

for(; d>=&bcd[0]; --d)
{
*s = *d + '0';
s++;
}
*s =0;
}


I certify that this code has passed my rigous "Worked twice in-a-row" test

Edited by - Magmai Kai Holmlor on December 28, 2001 12:43:09 PM
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Buster
Buster
Yeah I want change for a dollar, but you can''t use any coins.
ANSI2000
ANSI2000
Sorry I couldnt resist...

You say you dont want to use the c runtime atof to convert string to float...

But within your on parsing routines you use the c runtime strcpy functions...

Why even bother writting your own conversion function? Learning purposes? I know, you better then that Mag....
Stoffel
Stoffel
We''ve had to do this at work to develop embedded or kernel (NT device driver) software. No std library, and we alias strcpy, etc., to our own functions.
ATronic
ATronic
I always used atof.

Alex Broadwin
A-Tronic Software & Design
-----
"if you fail in life, you were destined to fail. If you suceed in life, call me."
"The answer is out there."
"Please help, I''m using Windows!"
Alex BroadwinA-Tronic Software & Design-----"if you fail in life, you were destined to fail. If you suceed in life, call me.""The answer is out there.""Please help, I'm using Windows!"
ATronic
ATronic
No, the other way around.

Alex Broadwin
A-Tronic Software & Design
-----
"if you fail in life, you were destined to fail. If you suceed in life, call me."
"The answer is out there."
"Please help, I''m using Windows!"
Alex BroadwinA-Tronic Software & Design-----"if you fail in life, you were destined to fail. If you suceed in life, call me.""The answer is out there.""Please help, I'm using Windows!"
Shannon Barber
Shannon Barber
strcpy is a safe (and efficent) routine to use in a reentrant function (and trivial to reimplement if required) - sprintf isn''t.

And I would need a ftoa function :p

...
BTW, if you ever need to multiple a float by an interger - don''t convert the interger into a float first. There''s an opcode that does both fimul
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Shannon Barber
Shannon Barber
What was I suppose to find there?

Am I the only one on the planet that ever wanted to convert a float TO a string?
The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.