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.
You could cast
float value = 2.75f;
int valueTruncated = (int) value;
float value2 = valueTruncated;
float value3 = value - value2;
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With