I'm using replaceAll() to remove all the "00" from the given String. Though it's removing all the 00, it is also removing a preceding character.
String a = "2400.00";
String a1 = a.replaceAll(".00", "");
I expected 24 as o/p but got 2.
I'm using replaceAll() to remove all the "00" from the given String. Though it's removing all the 00, it is also removing a preceding character.
String a = "2400.00";
String a1 = a.replaceAll(".00", "");
I expected 24 as o/p but got 2.
The . means any character in regex. replaceAll uses a regex as arugment. Please escape it. a.replaceAll("\\.00", "");
Or just simply use replace(".00", "").
replaceAll takes regex as first argument. In regex sytax .(dot) means ANY character, thus the result.
Either escape that dot with \\ or use replace instead of replaceAll (replace still replaces all occurences, but argument is "pattern" to replace, not regex)
This is because . cmatches any character in regex (well, except for the newline character, but it can be changed with appropriate flag).
That's why it matches 400 as well as .00 and replaces it.
What you need is to replace 00 or .00, so you need pattern: \.?00
Explanation:
\.? - match . zero or one time
00 - match 00 literally
Code:
String a = "2400.00";
String a1 = a.replaceAll("\\.?00", "");
System.out.println(a1);