简体   繁体   中英

Position of first significant digit after the decimal point

How can I calculate the position of the first significant digit in a fraction?

Here are a few example inputs with desired output

0.123456    // 1st sign. number position = 1
0.0012345   // ...                       = 3
0.000012345 // ...                       = 5

No need for looping. You can simply use the following formula:

Math.ceil(-Math.log10(d))

Example:

public static int firstSignificant(double d) {
    return (int) Math.ceil(-Math.log10(d));
}

// Usage
System.out.println(firstSignificant(0.123456));    // 1
System.out.println(firstSignificant(0.0012345));   // 3
System.out.println(firstSignificant(0.000012345)); // 5

A note on some corner cases:

  • 0 has no first significant digit. For this case the formula evaluates to Integer.MAX_VALUE .
  • You haven't specified what should happen with negative values, but if you want them to behave like positive values you can use Math.abs(d) instead of d in the formula.

You could loop over it count the number of times you need to multiply by ten before it becomes greater or equal to one:

public static int significantDigitNum (double d) {
    int cnt = 0;
    while (d < 1) {
        d *= 10;
        ++cnt;
    }
    return cnt;
}

EDIT:
As David Conrad commented, this function will only work for positive numbers. To also support negatives:

public static int significantDigitNum (double d) {
    int cnt = 0;
    d = Math.abs(d);
    while (d < 1) {
        d *= 10;
        ++cnt;
    }
    return cnt;
}

You can check each character if it is a number between 1-9.

    String numberString = "0.000012345";
    int position = 1;
    for(int i=0;i<numberString.length();i++){           
        if(String.valueOf(numberString.charAt(i)).matches("[1-9]")){
            position=i-1;
            break;
        }
    }

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