Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Floating Point Numbers

I have a variable of type double, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...

eg. I need

2.5 // not 2.500
2   // not 2.000
1.375 // exactly till 3 decimals
2.12  // not 2.120

I tried using DecimalFormatter, Am i doing it wrong?

DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);

Thanks. :)

like image 721
st0le Avatar asked Jan 19 '11 08:01

st0le


People also ask

What is the format specification for a floating-point number?

Use power-of-ten exponential notation, like 2.3e+05, to print the number. The precision specifies the number of decimal places to display in the mantissa, and usually defaults to 6. Use either the " f " or the " e " format, depending on the size of the number to be printed.

How do I format a floating-point number in Python?

Format float value using the round() Method in Python The round() is a built-in Python method that returns the floating-point number rounded off to the given digits after the decimal point. You can use the round() method to format the float value.

How do you write a floating-point number?

Like scientific notation, floating-point numbers have a sign, mantissa (M), base (B), and exponent (E), as shown in Figure 5.27. For example, the number 4.1 × 103 is the decimal scientific notation for 4100. It has a mantissa of 4.1, a base of 10, and an exponent of 3.

How do you format a float upto 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


2 Answers

Try the pattern "0.###" instead of "0.000":

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("0.###");
        double[] tests = {2.50, 2.0, 1.3751212, 2.1200};
        for(double d : tests) {
            System.out.println(df.format(d));
        }
    }
}

output:

2.5
2
1.375
2.12
like image 187
Bart Kiers Avatar answered Sep 25 '22 21:09

Bart Kiers


Your solution is almost correct, but you should replace zeros '0' in decimal format pattern by hashes "#".

So it should look like this:

DecimalFormat myFormatter = new DecimalFormat("#.###");

And that line is not necesary (as decimalSeparatorAlwaysShown is false by default):

myFormatter.setDecimalSeparatorAlwaysShown(false);

Here is short summary from javadocs:

Symbol  Location    Localized?  Meaning
0   Number  Yes Digit
#   Number  Yes Digit, zero shows as absent

And the link to javadoc: DecimalFormat

like image 21
Marcin Pieciukiewicz Avatar answered Sep 24 '22 21:09

Marcin Pieciukiewicz