2

How to extract the hundred of an int variable? For example, I have a random number:

int i = 5654217;

I want code to extract the number "2".

I tried to do

i/100

Which gave me 56542.

But I can't find a way to extract only the last number.

Too, I'm really unsure this is the best way to extract the hundred of the variable.

Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
Natacha BK
  • 137
  • 1
  • 8
  • 5
    `(i / 100) % 10` – Thiyagu Dec 10 '19 at 17:05
  • first parse the int to string (https://www.geeksforgeeks.org/different-ways-for-integer-to-string-conversions-in-java/) than get an specific char (number) in a string (https://beginnersbook.com/2013/12/java-string-charat-method-example/) than you convert this char back to int (https://alvinalexander.com/java/edu/qanda/pjqa00010.shtml) – Idemax Dec 10 '19 at 17:07
  • 2
    Does this answer your question? [Get a specific digit of a number from an int in Java](https://stackoverflow.com/questions/9253716/get-a-specific-digit-of-a-number-from-an-int-in-java) – hat Dec 10 '19 at 17:09
  • @MarceloFilho thats a way too complicated and inefficient way around what user7 suggested – Clashsoft Dec 10 '19 at 17:35
  • Make up your mind. Hundreds, as per your question and example, or hundredths, as per your title? – user207421 Dec 11 '19 at 06:16

3 Answers3

1

I am not 100% sure what you are asking so I will put the two guesses that I have of what your question is. If it doesn't answer your question please feel free to let me know, I will help you.

1) You are dividing an integer (int) by 100 and the last 2 digits disappear.

double x = (double)i/100.0;
//ints cannot store a decimal

2) You have a decimal (double) and are trying to output hundreds digit.

public int hundredthsDigit(double x){
    if(x>0.0) return (x/100)%10; 
    //This moves the 100s digit to the 1s digit and removes the other digits by taking mod 10
    return 10-Math.abs(x/100)%10;
    // does practically the same thing, but is a work around as mod doesn't work with negatives in java
}
0

The modulus operator, % effectively gives you the remainder of a division.

You can get the last digit by getting the number, mod 10. Try (i / 100) % 10

You can read up more on modular arithmetic and such here: https://en.m.wikipedia.org/wiki/Modular_arithmetic

iPhoenix
  • 719
  • 7
  • 20
0

Please find code below:

    package com.shree.test;

public class FindNumber {

    public static int findNumberAt(int location,int inputNumber) {
        int number = 0;

        //number =  (inputNumber % (location*10))/location;    // This also works
        number =  (inputNumber/location)%10; // But as mentioned in other comments and answers, this line is perfect solution 

        return number;

    }

    public static void main(String[] args) {
        System.out.println(findNumberAt(100, 5654217));
    }
}
Shrirang Kumbhar
  • 363
  • 4
  • 17