Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equals() and indexOf() not working as I'd expect using NumberFormat

I'm attempting to check if a string(filter) is contained in another string(formattedAmount) i.e. is filter a substring of formattedAmount.

I could not get it to work so I just changed the code to use "equals()" instead of "indexOf()", purely for simplyfing the testing. The equals method does not appear to be working as I would expect either.

Here is a dummy script I wrote up that replicates what I am trying to do:

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;


public class utils
{

    public utils()
    {
    }

    public static void main(String[] args) throws Exception 
    {   
        String filter = "333 333,44";
        Number amount = new BigDecimal(333333.44);

        NumberFormat nf = NumberFormat.getNumberInstance(Locale.FRANCE);
        nf.setMinimumFractionDigits(2);

        String formattedAmount = nf.format(amount);

        if (formattedAmount.equals(filter)) 
        {
            System.out.println("Working");
            }
    }
}

Any Ideas why it is not entering the If statement?

Thanks

like image 888
Thomas Buckley Avatar asked Jan 25 '12 17:01

Thomas Buckley


2 Answers

A simple println will reveal the truth: the FRANCE locale thousands separator is NOT THE SPACE CHARACTER:

System.out.println((int)formattedAmount.charAt(3) + " " + (int)filter.charAt(3));

Prints:

160 32

Hence, your two strings are not equal.

Try

char s = 160;
String filter = "333" + s + "333,44";
like image 149
Tudor Avatar answered Sep 23 '22 00:09

Tudor


String#equals lexicographically compares two strings. So for equals to return true both strings must have the same content. Just checked that two strings have different characters: formattedAmount = 33 33 33 c2 a0 33 33 33 2c 34 34 vs filter = 33 33 33 20 33 33 33 2c 34 34. 0x20 is the standard space and 0xc2a0 is probably no-break-space. No wonder equals return false - the strings have different characters after the first three '3's.

like image 23
Andrei LED Avatar answered Sep 25 '22 00:09

Andrei LED