user4307551
user4307551

Reputation:

Adding a trailing 0 to my 0.1, 0.2 values, but not to my 0.25 values

I have a double value that is pulled in from an external method call. When a 0.6 value comes through, I want it to be changed into 0.60, but I don't wan't to put "0" at the end of my string or else it will make my 0.65 values 0.650.

I had a problem before where it displayed 1.95 as 195000001, but I have fixed this problem.

double convPrice = callMethod.totalPriceMethod(); //Calls value from external method and adds to local variable.

totalPrice = Double.toString(convPrice); //local variable is converted to String
totalPrice = String.format("£%.2f", totalPrice ); //Formatting is applied to String
totalPriceLabel.setText(totalPrice); //String is added to JLabel.

Any help would be greatly appreciated.

Upvotes: 0

Views: 134

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Simply use String.format format specifier for floating point numbers:

String.format("%.2f", yourNumber)

Tutorial at: Formatting tutorial.

Or use a DecimalFormat object.


e.g.,

  String s = String.format("%.2f", 0.2);
  System.out.println(s);

Don't convert double to String pre-formatting as that's what the formatting is for. You're doing this

double convPrice = callMethod.totalPriceMethod();
totalPrice = Double.toString(convPrice); 
totalPrice = String.format("£%.2f", totalPrice ); 
totalPriceLabel.setText(totalPrice); 

When you want to do something like this:

double convPrice = callMethod.totalPriceMethod();
// totalPrice = Double.toString(convPrice);  // ???????
totalPrice = String.format("£%.2f", convPrice); 
totalPriceLabel.setText(totalPrice); 

Since you're converting to currency, perhaps even better is to use a NumberFormat currencyInstance.

e.g.,

  NumberFormat currencyInstance = NumberFormat.getCurrencyInstance(Locale.UK);
  double convPrice = callMethod.totalPriceMethod();
  totalPriceLabel.setText(currencyInstance.format(convPrice));

Upvotes: 1

Related Questions