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

389 Views Asked by At

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

  • 1447948--> 1400000
  • 21163176-->21000000
  • 95999-->95000

How can I make this with using java?

3

There are 3 best solutions below

3
azro On BEST ANSWER

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

3
Karol Katanowski On

You can do it for any number by treating it as a string:

int number = 1447948;
String number1 = String.valueOf(number);
String[] split = number1.split("");
StringBuilder number2 = new StringBuilder();
for (int i = 0; i < split.length; i++) {
  if(i > 1)
    number2.append("0");
  else
    number2.append(split[i]);
}
int result = Integer.parseInt(number2.toString());
System.out.println(result);
0
blhsing On

Math is your friend.

int magnitude = (int) Math.pow(10, Math.log10(n) - 1)
int o = (int) Math.floor(n / magnitude) * magnitude

where n is the input number and o is the output number.