简体   繁体   中英

Getting the Nth digit after the decimal point

How can I get the Nth digit from a decimal number after the decimal point?

For example:

If the decimal number is 64890.1527 , then the 1st digit is 1 2nd digit is 5 , 3rd digit is 2 , and so on.

Getting the Nth Decimal of a Float

Here is a trick for getting the Nth decimal place of a float:

  • Take the absolute value
  • Multiply by 10 n
  • Cast to an int
  • Modulus by 10

Example

Get the third decimal of 0.12438. We would expect the answer to be 4.

  • 0.12438
    • Take the absolute value
  • 0.12438
    • Multiply by 10 3
  • 124.38
    • Cast to an int
  • 124
    • Modulus by 10
  • 4

How It Works

Multiplying by 10 n gets the decimal you care about into the ones place. Casting to an int drops the decimals. Modulus by 10 drops all but the ones place.

We take the absolute value in case the input is negative.

Code Snippet

float num = 0.12438f;
int thirdDecimal = (int)(Math.abs(num) * Math.pow(10,3)) % 10; // Equals 4
int fifthDecimal = (int)(Math.abs(num) * Math.pow(10,4)) % 10; // Equals 3

Not sure if this is the best solution, but...

Make a string of it; Loop through the string; Check what you wanna check.

You can take a Double and call toString on it and then iterate over charArray like this

public class TestIndexOf {
    public static void main(String[] args) {
        Double d = 5.26;
        String source = d.toString();

        char[] chars = source.toCharArray();

        char max = source.charAt(source.length() - 1);
        boolean isMax = true;
        for (char aChar : chars) {
            if (max < aChar) {
                max = aChar;
                isMax = false;
            }
        }
        System.out.println(max + " is max?" + isMax);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM