Pregunta

I am trying to figure out how to, given a decimal through a String calculate the number of significant digits so that I can do a calculation to the decimal and print the result with the same number of significant digits. Here's an SSCCE:

import java.text.DecimalFormat;
import java.text.ParseException;

public class Test {

    public static void main(String[] args) {
        try {
            DecimalFormat df = new DecimalFormat();
            String decimal1 = "54.60"; // Decimal is input as a string with a specific number of significant digits.
            double d = df.parse(decimal1).doubleValue();
            d = d * -1; // Multiply the decimal by -1 (this is why we parsed it, so we could do a calculatin).
            System.out.println(df.format(d)); // I need to print this with the same # of significant digits.
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

I know DecimalFormat is to 1) tell the program how you intend your decimal to be displayed (format()) and 2) to tell the program what format to expect a String-represented decimal to be in (parse()). But, is there a way to DEDUCE the DecimalFormat from a parsed string and then use that same DecimalFormat to output a number?

¿Fue útil?

Solución

Use BigDecimal:

        String decimal1 = "54.60"; 
        BigDecimal bigDecimal = new BigDecimal(decimal1);
        BigDecimal negative = bigDecimal.negate(); // negate keeps scale
        System.out.println(negative); 

Or the short version:

        System.out.println((new BigDecimal(decimal1)).negate());

Otros consejos

Find it via String.indexOf('.').

public int findDecimalPlaces (String input) {
    int dot = input.indexOf('.');
    if (dot < 0)
        return 0;
    return input.length() - dot - 1;
}

You can also configure a DecimalFormat/ NumberFormat via setMinimumFractionDigits() and setMaximumFractionDigits() to set an output format, rather than having to build the pattern as a string.

int sigFigs = decimal1.split("\\.")[1].length();

Computing the length of the string to the right of the decimal is probably the easiest method of achieving your goal.

If you want decimal places, you can't use floating-point in the first place, as FP doesn't have them: FP has binary places. Use BigDecimal, and construct it directly from the String. I don't see why you need a DecimalFormat object at all.

You could convert a number string to a format string using regex:

String format = num.replaceAll("^\\d*", "#").replaceAll("\\d", "0");

eg "123.45" --> "#.00" and "123" --> "#"

Then use the result as the pattern for a DecimalFormat

Not only does it work, it's only one line.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top