3

How to separate double into two integer number? First number before and second number after decimal point. For example:

            double doub = 543.345671;
            int num1 = (int) doub; //543
            int num2 = getNumAfterDecimal(doub-num1); //return 345671

I need decimal part to integer.

5 Answers5

3

Use Double.toString() to map the double to a String : Double.toString(doub) then use String.split("\\.") to get the different parts as Strings. Then, optionally, Integer.valueOf() to parse those values as Integers :

double doub = 543.345671;
// Here, you want to split the String on character '.'
// As String.split() takes a regex, the dot must be escaped. 
String[] parts = Double.toString(doub).split("\\.");
System.out.println(Integer.valueOf(parts[0]));
System.out.println(Integer.valueOf(parts[1]));

Output :

543
345671
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
2

Get it using regex split,

double doub = 543.345671;
String data[] = String.valueOf(doub).split("\\.");
System.out.println("Before decimal: " + Integer.parseInt(data[0]) + ", After decimal: " + Integer.parseInt(data[1]));

Prints,

Before decimal: 543, After decimal: 345671
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
2

As I see,

Double d=543.345671;
String line=String.valueOf(d);
String[] n=line.split("\\.");
int num1=Integer.parseInt(n[0]);
int num2=Integer.parseInt(n[1]);
Dred
  • 1,076
  • 8
  • 24
  • It's not bad, but i lose zeros after decimal point. For example: if d=35.0067 i get num2=67 and don't know now many zeros i lost. – Yaroslav Nudnenko Apr 05 '19 at 09:37
  • 1
    Yes, because int lose leading zeros, If it needs zero at start it shouldn't convert to int and be stayed like string – Dred Apr 05 '19 at 09:50
2

It depends how many digits you want after the decimal point, but this is the gist:

double d = doub - (int)doub; // will give you 0.xyz
int result = d * 1000; // this is for 3 digits, the number of zeros in the multiplier decides the number of digits 
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
1

That's what I need. Thank, Nir Levy! But sometimes rounding errors are possible.

    double doub = 543.04;
    int num1 = (int) doub; //543
    int num2 = (int) ((doub-num1)*1000000); //39999

I added Math.round() to get the decimal part correctly.

    double doub = 543.04;
    int num1 = (int) doub; //543
    int num2 = (int) Math.round((doub-num1)*1000000); //40000