Floating point format in java

Asked

Viewed 1,267 times

0

Personal how do I read a floating point with a specific limit of decimal places after the comma? For example, read 3.14?

Note: I know you can format the value of a variable with decimal format, but I need to receive values with only two decimal places already in reading.

  • By specific limit of decimals, do you mean that there will always be two? How are you reading this value? The user enters it via Scanner?

  • The only method I know is via Scanner, and yes, the dairy always follows a pattern of quantity, for example, values with 2 boxes after the comma.

  • OK about that one. Another point, you said "I need to receive values with only two decimal places already in reading" that means if the person type 3.142 is to read only 3.14? Or should something different happen if the input is not the way you need it?

1 answer

1


It is possible to do this with a combination of Decimalformat and Double.parseDouble(). I created a custom Double called Formatteddouble that extends Decimalfloat to accomplish what you want. See the class code:

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

public class FormattedDouble extends DecimalFormat {

    private static final long serialVersionUID = 1L;
    private DecimalFormatSymbols symbols;
    private String stringValue;
    private double value;

    public FormattedDouble(double value) {
        super("#.##"); // Customize the format here.
        symbols = new DecimalFormatSymbols();
        symbols.setDecimalSeparator('.');
        symbols.setGroupingSeparator(' ');
        setDecimalFormatSymbols(symbols);
        this.setStringValue(format(value));
        this.setValue(Double.parseDouble(this.getStringValue()));
    }

    public double getValue() {
        return value;
    }

    public void setValue(double value) {
        this.value = value;
    }

    public String getStringValue() {
        return stringValue;
    }

    public void setStringValue(String stringValue) {
        this.stringValue = stringValue;
    }

}

That said, getting a Double with the number of limited houses (using the example you gave), is simple:

public class Main {

    public static void main(String[] args) {
        double example = new FormattedDouble(3.1412233).getValue(); // Returns 3.14.
        System.out.println(example); // Outputs 3.14.
    }

}

You can adapt the Formatteddouble class to allow changes in the number of houses. Read the documentation from Decimalformat to be able to adapt to your needs.

EDIT:

Is not exactly what you want, because it is not possible. A Double is a Double, and point (If you want change the format, accurate format). It is possible to simulate what you want, the change at the "moment of reading", creating a custom Double, as I did.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.