Getting the Nth Decimal of a Float

前端 未结 3 1650
长情又很酷
长情又很酷 2021-01-17 08:16

I was trying to compare between decimals in floats using if statements, but I don\'t know how to do it. I searched a lot but didn\'t get the answer.

For example:

相关标签:
3条回答
  • 2021-01-17 08:19

    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 10n
    • 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 103
    • 124.38
      • Cast to an int
    • 124
      • Modulus by 10
    • 4

    How It Works

    Multiplying by 10n 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
    
    0 讨论(0)
  • 2021-01-17 08:36

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

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

    0 讨论(0)
  • 2021-01-17 08:39

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题