I am trying to round off an user input double value to two decimal places for which I am using the Decimal Format class. This works fine until the user inputs the value 0. Then, instead of giving an output such as 0.00 (2 decimal places), I get 0.0. Why does this happen? Is there an alternative method?
Why do people still use DecimalFormat when you can write this?
System.out.printf("%.2d%n", myDouble); Don't copy‑and‑paste that code.
posted 1 year ago
I am currently not comfortable with the syntax and functionality of printf. I need some practice to get used to it. But, why do I get a run time exception:
at java.util.Formatter$FormatSpecifier.checkInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.<init>(Unknown Source)
at java.util.Formatter.parse(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.io.PrintStream.format(Unknown Source)
at java.io.PrintStream.printf(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
while implementing this:
Isn't line 8 supposed to round off the value to two decimal places?
%f does the job here but what is %.2d supposed to do? What kind of values can it handle? I am sorry but I don't quite understand how printf works. Can I get some links/resources to gain a thorough understanding?
Khusbu Sinha wrote:
%f does the job here but what is %.2d supposed to do? What kind of values can it handle?
The precision field is not applicable with integral types. As for what is an integral type, they are (can be applied to) ... byte, Byte, short, Short, int and Integer, long, Long, and BigInteger (see JavaDoc link below).
Khusbu Sinha wrote:Can I get some links/resources to gain a thorough understanding?
The JavaDoc has a good chart / table that list everything...
If you want to return a value with a set number of decimal places use BigDecimal. You'll still need to format it when printing. If you want to pass around the formatted version you'd have to do that as a String. The String class has a format() method that behaves the same as printf() but generates a formatted String instead of printing it.
You have the right to remain sentient. If you give up the right to remain sentient,
you will be elected to public office.
posted 1 year ago
There is no such thing as a double with a specific number of decimal places. You would have to convert the double to a String and return a String with a decimal point two places from its right end. You cannot return a “formatted” double.