Splitting double into integers

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

How can I split Double into two integers like the following example :

2.34 -> 2 and 34 (I dont want the modf() result that gives 2 and 0.34)

Hugo
 
Well, first off, how are you going to deal with trailing zeros? Note that "2
and 34" is the same as "2 and 340". I'll assume you don't want trailing
zeros.

You say you can get it to where you've got "2 and .34". Ok, you're more than
half way there. You want to know the number of digits in the fractional
part, and then multiply it by 10 to that power. To get the number of digits
is easy:

int Digit_Count( double value )
{
return (value.ToString())->Length ;
}

Note this will include the decimal point, so subtract one from this. So, you
want to do this (using your example):

34 = .34 * pow( 10, Digit_Count( .34 ) - 1 ) ;

Now just use variables where the "34" and ".34" are...

[==P==]
 
How about this:

double f = 2.34;
int whole = (int) f;
int decimal = (f - whole) * 100;

Cheers,
Mark

Peter Oliphant said:
Well, first off, how are you going to deal with trailing zeros? Note that "2
and 34" is the same as "2 and 340". I'll assume you don't want trailing
zeros.

You say you can get it to where you've got "2 and .34". Ok, you're more than
half way there. You want to know the number of digits in the fractional
part, and then multiply it by 10 to that power. To get the number of digits
is easy:

int Digit_Count( double value )
{
return (value.ToString())->Length ;
}

Note this will include the decimal point, so subtract one from this. So, you
want to do this (using your example):

34 = .34 * pow( 10, Digit_Count( .34 ) - 1 ) ;

Now just use variables where the "34" and ".34" are...

[==P==]

H.B. said:
Hi,

How can I split Double into two integers like the following example :

2.34 -> 2 and 34 (I dont want the modf() result that gives 2 and 0.34)

Hugo
 
H.B. said:
Hi,

How can I split Double into two integers like the following example :

2.34 -> 2 and 34 (I dont want the modf() result that gives 2 and 0.34)

Do you want 2.340000001 to be 2 and 340000001 or 2 and 34? E.g. do you
specifically want the two integers to be units and hundreths, or
hundreths and, basically, the string representation of the fractional
part turned into an int? What about range issues, for example if your
number is outside the range of int (double has a huge range compared to
int)?

Why do you need the split anyway?

Tom
 
Back
Top