Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop DecimalFormat with percentage sign from moving the decimal

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 %
like image 791
ryvantage Avatar asked Jan 14 '14 20:01

ryvantage


People also ask

What is the Tostring format code for percentage?

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.

How do you format a float?

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.

What is DecimalFormat?

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.


2 Answers

Surround your % with single quotes:

DecimalFormat df2 = new DecimalFormat(" #,##0.00 '%'");
like image 117
StoopidDonut Avatar answered Oct 06 '22 13:10

StoopidDonut


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 %
like image 7
Mike B Avatar answered Oct 06 '22 13:10

Mike B