5

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.

4 Answers 4

6

You could cast

float value = 2.75f;
int valueTruncated = (int) value;
float value2 = valueTruncated;
float value3 = value - value2;
0
5

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.

0
2

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
4
  • And what if decimals are splits by ","? Hello ArrayIndexOutOfBoundsException?
    – Stan
    Commented Sep 1, 2015 at 11:35
  • Well @Stan, I'm not sure about "," but the question asks for values containing ".". I'm sorry I'm not very pro in Java yet, but I'm always eager to learn...
    – instanceof
    Commented Sep 1, 2015 at 12:09
  • I just wanna say that in different locales the comma sign is different. I mean the "splitter char" between decimals and float parts. For example in US its "," while in Germany its "." meaning that code has to work locale independently. Your code gonna crash running with US locale since there will be no dots and thus you'll get ArrayIndexOutOfBoundsException.
    – Stan
    Commented Sep 3, 2015 at 16:20
  • Ah okay cool, thanks for pointing that out. I didn't know that.
    – instanceof
    Commented Sep 4, 2015 at 10:25
2

if the input is 59.38 result is n1 = 59 n2 = 38 this is what I came up with:

    int n1, n2 = 0; 
    Scanner scan = new Scanner(System.in);
    double input = scan.nextDouble();

    n1 = (int) input;
    n2 = (int) Math.round((input % 1) * 100);

Not the answer you're looking for? Browse other questions tagged or ask your own question.