Home > Mobile >  How to leave only 4 decimals after number bigger than 0?
How to leave only 4 decimals after number bigger than 0?

Time:10-09

I don't know how to explain this well, but for example I have a number: 0.00000548347554 and want to make 0.000005483 from it, or 0.0683453248 to 0.06843, etc.

CodePudding user response:

This assumes your number is a string:

String tmp = "0.0683453248";

String[] tmpA = tmp.split("");
ArrayList<String> res = new ArrayList<>();

for(int i = 0; i < tmpA.length; i  ){
    res.add(tmpA[i]);

    if(!tmpA[i].equals(".") && Integer.parseInt(tmpA[i]) > 0){
        res.add(tmpA[i   1]);
        res.add(tmpA[i   2]);
        res.add(tmpA[i   3]);
        break;
    }

}

String result = String.join("",res);

CodePudding user response:

Using the solution from this answer, you can convert the given number into a string and then use the regex replacement to get the required string out of it.

Demo:

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(doubleToString(0.00000548347554));
        System.out.println(doubleToString(0.0683453248));
    }

    static String doubleToString(double n) {
        DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
        df.setMaximumFractionDigits(340);
        return df.format(n).replaceAll("(\\d*\\.0*[1-9]{4})\\d*", "$1");
    }
}

Output:

0.000005483
0.06834

ONLINE DEMO

Explanation of the regex:

  • (: Start of capturing group#1
    • \\d*\\.: Digit(s) followed by .
    • 0*: Any number of zeros
    • [1-9]{4}: Non-zero four digits
  • ): End of capturing group#1
  • \d* : Any digit any number of times

CodePudding user response:

For small numbers BigDecimal can be used:

BigDecimal significant(double number, int count) {
    if (count < 1) 
        throw new IllegalArgumentException("invalid count: "   count);
    BigDecimal big = BigDecimal.valueOf(number);
    if (big.precision() <= count) {
        return big;
    } else {
        return big.setScale(big.scale()-big.precision() count, RoundingMode.HALF_EVEN);
    }
}

precision() returns the number of significant digits;
the method changes the scale so only the desired number of digits is present.
The if is used to avoid more zeros than the input if this has less than count digits.

Use doubleValue() to convert the result to double if needed (may suffer from rounding error).
To get a string, use toPlainString(), which will transform the result to string without using the exponential notation.

Rounding mode can also be changed if desired.

Note: it can also be used with larger numbers, it basically will replace digits by zero like in significant(12345,2) -> 12000 (or 1.2E 4)

  •  Tags:  
  • java
  • Related