I want to separate float value from decimal point.
for ex:
Float f = 3.5
than i want
int value1 = 3
int value2 = 5
and if f = 4.0 than,
int value1 = 4
int value2 = 0
But please i could not do this with string manipulations. like Split
Thanks
asked Apr 28, 2011 at 17:12
djk
3,6819 gold badges34 silver badges40 bronze badges
-
1What do you want value2 to be if there's more than one decimal place, e.g 3.54321?NickT– NickT2011年04月28日 17:20:08 +00:00Commented Apr 28, 2011 at 17:20
2 Answers 2
simply you can do is
int integer_part=(int)f;
float float_part=(f-integer_part);
string string_f=f+"";
int float_part=f*(string_f.length()-1)*10
answered Apr 28, 2011 at 17:27
Sunil Pandey
7,1027 gold badges38 silver badges48 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
John Leehey
you have 2 variables of different types with the same name. Other than that, its an interesting solution
Matt
This will have the same problem as John's solution, i.e. if f > Integer.MAX_VALUE, you cannot cast it to a useful int.
Sunil Pandey
you can use long, by the way do you have any problem in using string
Sunil Pandey
if you can be specific to your problem then we could provide some solution. so plz edit and provide more details about your problem
If you simply want the ones digit in value 1 and the tenths digit in value 2, you can do this:
value1 = (int)f;
value2 = ((int)(f * 10)) % 10;
answered Apr 28, 2011 at 17:24
John Leehey
22.3k9 gold badges63 silver badges90 bronze badges
3 Comments
John Leehey
@Matt, true, it would overflow. Then he could do f = f - value1; first for value2, that would work.
Matt
The first line would still not work, i.e. casting a float > Integer.MAX_VALUE to an integer would never work. So value1 would never be accurate.
John Leehey
In that case, there would be no solution then, except to cast it to a long. I think that might be over-analyzing this issue a bit.
default