javaregexconvertersdigit

Except two digits,make all the digits of integer to zero-Java


I have some integer values like 1447948,21163176,95999 and I wanna make them like that:

How can I make this with using java?


Solution

  • Because rounding is something that is count from the right, you cannot use it, you can just pass from string and use a basic regex to replace the non-2 first digits by 0 :

    int val = 1447948;
    int res = Integer.valueOf((""+val).replaceAll("(?<=\\d{2})\\d", "0"));
    //  res : 1400000
    

    (?<=\\d{2})\\d match the digits that have two digits before them

    Workable Demo