Is there a way to prevent a DecimalFormat
object from automatically moving the decimal place two places to the right?
This code:
double d = 65.87;
DecimalFormat df1 = new DecimalFormat(" #,##0.00");
DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
System.out.println(df1.format(d));
System.out.println(df2.format(d));
produces:
65.87
6,587.00 %
But I'd like it to produce:
65.87
65.87 %
The percent ("P") format specifier is used to multiply a number by 100. It converts the number into a string representing a % (percentage). In the same way, using (“P1”), would only include a single vale after decimal-point.
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 %. 2f, f is for floating point number, which includes both double and float data type in Java.
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.
Surround your % with single quotes:
DecimalFormat df2 = new DecimalFormat(" #,##0.00 '%'");
By default when you use a %
in your format string the value to be formatted will be first multiplied by 100. You can change the multiplier to 1 using the DecimalFormat.setMultiplier()
method.
double d = 65.87;
DecimalFormat df2 = new DecimalFormat(" #,##0.00 %");
df2.setMultiplier(1);
System.out.println(df2.format(d));
produces
65.87 %
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