Java – Displays currency formatting issues

Displays currency formatting issues… here is a solution to the problem.

Displays currency formatting issues

First post. In general, I’m brand new to software development and have spent hours trying to figure this out. As you can see, I’m converting double to String and then assigning that value to textResult(String).I format it correctly to show decimals, but I don’t know how to display as currency.

Based on what I found online, it looks like I might have to use it

NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

Then somehow used nf.format() but it didn’t work for me. Any guidance would be appreciated.

public void onCalculateDealOne(View v) {

get values from text fields
    EditText priceEntry = (EditText) findViewById(R.id.etListPriceDealOne);
    EditText unitsEntry = (EditText) findViewById(R.id.etNumberOfUnitsDealOne);
    EditText couponEntry = (EditText) findViewById(R.id.etCouponAmountDealOne);

get value from result label
    TextView result = (TextView) findViewById(R.id.perUnitCostDealOne);

assign entered values to int variables
    double price = Double.parseDouble(priceEntry.getText().toString());
    double units = Double.parseDouble(unitsEntry.getText().toString());
    double coupon = Double.parseDouble(couponEntry.getText().toString());

create variable that holds the calculated result and then do the math
    double calculatedResultDealOne = (price - coupon) / units;

convert calculatedResult to string
    String textResult = String.format("%.3f", calculatedResultDealOne);
    result.setText(textResult + " per unit");
    dealOneValue = calculatedResultDealOne;

hide the keyboard
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

make deal one label visible
    result.setVisibility(View.VISIBLE);

}

Solution

There are two simple solutions to this. You can use either the DecimalFormat object or the NumberFormat object.

I personally prefer the Decimalformat object because it gives you more precise control over the format of the output value/text.

Some people may prefer the NumberFormat object because the .getcurrencyInstance() method prefers cryptic string formats (e.g. “$#.00”, “# 0.00”)

public static void main(String[] args) {
    Double currency = 123.4;
    DecimalFormat decF = new DecimalFormat("$#.00");
    
System.out.println(decF.format(currency));

Double numCurrency = 567.89;
    NumberFormat numFor = NumberFormat.getCurrencyInstance();
    System.out.println(numFor.format(numCurrency));
}

The output of this example program is as follows:

$123.40

$567.89

Related Problems and Solutions