QConscious
QConscious

Reputation: 87

String.format() and DecimalFormat not actually formatting

I've tried two different ways of formatting some numbers to show up similar to money, so to 2 decimal places. However, I have tried setting the EditText field to

EditText.setText (String.format("%.2f, number))

as well as:

DecimalFormat precision = new DecimalFormat("0.00");
EditText.setText(String.valueOf(precision.format(number));

and neither has seemed to do anything, everything still defaults as setting to a 1 decimal place, ie) 30.0, and if its anything else it will go to 3 or more decimal places ie) 30.243

Upvotes: 0

Views: 960

Answers (5)

LvN
LvN

Reputation: 711

Your code seems correct, However please have a look here,

  System.out.printf("Floating point number with 2 decimal digits: %.2f\n",1.21312939123); 
  System.out.printf("Floating point number with 3 decimal digits: %.3f\n",1.21312939123);
  System.out.printf("Floating point number with 8 decimal digits: %.8f\n",1.21312939123);
  System.out.printf("String: %s, integer: %d, float: %.6f", "Hello World",89,9.231435);

Output:

Floating point number with 2 decimal digits: 1.21
Floating point number with 3 decimal digits: 1.213
Floating point number with 8 decimal digits: 1.21312939
String: Hello World, integer: 89, float: 9.231435

Upvotes: 0

Arjun saini
Arjun saini

Reputation: 4182

Try this

DecimalFormat precision = new DecimalFormat("0.##");
edittext.setText(precision.format(number));

Upvotes: 1

RobinHood
RobinHood

Reputation: 10969

If you want to display 5.00 as 5 & 5.10 as 5.1 then use:

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

If you want to display 5.00 as 5.00 & 5.10 as 5.10 then use:

DecimalFormat formater = new DecimalFormat("#.00");

Upvotes: 1

Sathish Kumar J
Sathish Kumar J

Reputation: 4335

Try this,

        double rews = 100.89478;
        String ada = new DecimalFormat("##.##").format(rews);
        System.out.println(ada);

Output

100.89

Here .## so it will give 2 decimal points. if you want to add 3 means use .###.

Upvotes: 0

eLemEnt
eLemEnt

Reputation: 1801

@Mason Richardson

Have you tried setMinimumFractionDigits() which sets minimum fractions for your value

 DecimalFormat precision = new DecimalFormat("#.##");
 dec.setMinimumFractionDigits(2);
 EditText.setText(String.valueOf(precision.format(number));

Upvotes: 3

Related Questions