How to get the first digit after the decimal point of a float number in Java

1 Answer

0 votes
public class Program {

    /**
        Extracts the first digit after the decimal point of a float.
        Logic:

            float f = 13.6871f;
            int n = (int)(Math.floor(Math.abs(f) * 10)) % 10;

        Steps:
        1. Take absolute value.
        2. Multiply by 10 to shift the first decimal digit into the integer part.
        3. Floor the result.
        4. Cast to int.
        5. Use modulo 10 to isolate the digit.
    */
    public static int extractDecimalDigit(float f) {
        return (int)(Math.floor(Math.abs(f) * 10)) % 10;
    }

    public static void main(String[] args) {

        float f = 13.6871f;

        int n = extractDecimalDigit(f);

        System.out.println(n);
    }
}



/*
run:

6

*/

 



answered Aug 28, 2019 by avibootz
edited Sep 15 by avibootz

Related questions

...