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. :)
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.
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.
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.
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 %.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With