1

Suppose if I have 3.13 and 4.13, I want to be able to check whether .13 from 3.13 and .13 from 4.13.

I tried many things:

1) converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work

2) a = 3.14; a = a - Math.floor(a); to try to get the decimal alone but i end up getting 0.1400000001

Elmer
  • 180
  • 1
  • 2
  • 12
  • 1
    _converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work_ **:** `split` uses a regex, so you have to escape the dot. `string.split(".")` should become `string.split("\\.")`, try it and let me know if it works – BackSlash Sep 16 '13 at 11:22

4 Answers4

2

converting the two decimals to Strings and trying to split them up by ".", but I couldnt get that to work

split uses a regex, so you have to escape the dot.

string.split(".") 

should become

string.split("\\.")

With this you should be able to split the string properly and do your comparisons


By the way, i would use Reimenus solution, when you have numbers it's always better to use math if you can. Use strings only if you really need them.

Community
  • 1
  • 1
BackSlash
  • 21,927
  • 22
  • 96
  • 136
2

You could separate the fractional part for comparison instead

double value1 = 3.13;
double value2 = 4.13;
double fractional1 = value1 - (long)value1;
double fractional2 = value2 - (long)value2;
System.out.println(Double.compare(fractional1, fractional2));

Read What Every Computer Scientist Should Know About Floating-Point Arithmetic too see why you're seeing additional digits after your own numerical operation

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • +1! Using String operations for numbers is something I don't like. When playing with numbers, always do the MATH! – Rahul Sep 16 '13 at 11:31
0

your second method is actually correct. when comparing double values, you have to include a range.. Java: Double Value Comparison (refer this)

Community
  • 1
  • 1
Balaji Krishnan
  • 1,007
  • 3
  • 12
  • 29
0

Try this out

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        float v1 = 3.13f,v2 = 4.13f;
        //Converting float value into String array
        String split1[]=Float.toString(v1).split("\\.");
        String split2[]=Float.toString(v2).split("\\.");

        //Comparing two strings
        if(split1[1].equals(split2[1]))
        {
            System.out.println("Yes");
        } 
    }
}
Siddh
  • 712
  • 4
  • 21