Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split float in Java Android

Tags:

java

android

I have a number like 2.75. I want to split this number into two other floats. Here is an example of what I am searching for:

value = 2.75 
value2 = 2.0
value3 = 0.75

I need them in my algorithm, so how could I implement this? I found split() but it returns string. I need floats or integer at least.

like image 235
Anwar Avatar asked Jul 09 '14 16:07

Anwar


3 Answers

You could cast

float value = 2.75f;
int valueTruncated = (int) value;
float value2 = valueTruncated;
float value3 = value - value2;
like image 87
A--C Avatar answered Oct 01 '22 21:10

A--C


You can also try this

double value = 2.75;
double fraction=value%1;//Give you 0.75 as remainder 
int integer=(int)value;//give you 2 fraction part will be removed

NOTE: As result may very in fraction due to use of double.You better use

float fraction=(float) (value%1);

if fractional part is big.

like image 39
akash Avatar answered Oct 01 '22 21:10

akash


Another option is to use split():

double value = 2.75;
/* This won't work */// String[] strValues = String.valueOf(value).split(".");
String[] strValues = String.valueOf(value).split("\\.");
double val1 = Double.parseDouble(strValues[0]); // 2.0
double val2 = Double.parseDouble(strValues[1]); // 0.75
like image 37
instanceof Avatar answered Oct 01 '22 21:10

instanceof