Displaying Currency Format Issue - java

First post. I'm brand new to software development in general and have spent hours trying to figure this piece out. As you can see, I'm converting a double to a String, then assigning that value to textResult (String). I formatted it properly to display decimals, but I can't figure out how to show as currency instead.
Based on what i've found online, it looks like I may have to use
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
and then use nf.format() somehow but it just doesn't work for me. Any guidance would be greatly 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);
}

There are two simple solutions to this. You can use a DecimalFormat object, or you can use a NumberFormat object.
I personally prefer a Decimalformat object because it gives you more precise control over how you would like to format your output value/text.
Some may prefer the NumberFormat object because the .getcurrencyInstance() method is easier to understand than a cryptic string format (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 for this example program is below:
$123.40
$567.89

You need to use formatter to format the double value you want, eg:
double money = 202.2
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String moneyString = formatter.format(money);
System.out.println(moneyString);

Related

How to change a double to a string

I have an app which shows a string in an EditText, this string is the result of the operation of two other doubles the user types in two different EditTexts.
The problem is that I want the result of the operation to be shown in the third EditText, but for that it has to be a string. Therefore I change the result by the toString method.
The problem starts here, I want the double that will be a string to have only one decimal. For that I used DecimalFormat and created the df format "#.#". And then I changed the text that would be shown in the last EditText to the new double variable with only one decimal (obviously changing it to String).
DecimalFormat df = new DecimalFormat("#.#");
double BMI_trimmed = Double.parseDouble(df.format(BMI));
final EditText BMIResult = (EditText)findViewById(R.id.BMIResult);
BMIResult.setText(Double.toString(BMI_trimmed));
Here I leave you all the code of the myButtonListenerMethod:
public void myButtonListenerMethod(){
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final EditText heighText = (EditText)findViewById(R.id.heightInput);
String heighStr = heighText.getText().toString();
double height = Double.parseDouble(heighStr);
final EditText weighText = (EditText)findViewById(R.id.weightInput);
String weighStr = weighText.getText().toString();
double weight = Double.parseDouble(weighStr);
double BMI = (weight)/(height*height);
DecimalFormat df = new DecimalFormat("#.#");
double BMI_trimmed = Double.parseDouble(df.format(BMI));
final EditText BMIResult = (EditText)findViewById(R.id.BMIResult);
BMIResult.setText(Double.toString(BMI_trimmed));
}
});
}
This app runs perfectly on the AVD, I've runned it in three already. But when I run it in a real device and click the button that starts the myButtonListenerMethod, it stops working suddenly and shuts down. The Terminal gives the following error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bmicalculator, PID: 19058
java.lang.NumberFormatException: For input string: "24,2"
at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1306)
If anyone knows what the problem is, please tell me I'll try. Honestly I don't understand why it runs in the AVD but it doesn't properly in a real device. Any idea?
You already get the value rounded as you want and as a string from the formatter. Don't try to parse it, just display it.
BMIResult.setText(df.format(BMI));
The problem is probably your phone Locale. Some phones use . as a separator and some use , as separator. Try replacing all "," with "." before parsing from String to Double.
Also try using this answer:
https://stackoverflow.com/a/7559011/2249224
double BMI_trimmed = Double.parseDouble(df.format(BMI));
String yourResult = String.valueOf(BMI_trimmed);
Happy coding

Decimal Format in Jframe?

I am making a pizza calculator but my results come out as "$7.5" instead of "$7.50". I have this decimal format code written out with my code below it, but it doesn't seem to work. Any ideas?
private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
double diameter;
double labourCost = 1.00;
diameter = Double.parseDouble(diameterInput.getText());
double storeCost = 1.50;
double materialsCost = 0.50 * diameter;
double totalCost = labourCost + storeCost + materialsCost;
DecimalFormat x = newDecimalFormat("0.00");
costOutput.setText("The cost of the pizza is $" + totalCost);
You're not using the result ("x") of the operation for anything. I'm guessing that replacing "totalCost" with "x" in the last line will help?
You need to use a Decimal Formatter to convert your floating point value over to a string.
// Make a new formatter with your format
DecimalFormat myFormatter = new DecimalFormat("$##.00");
// Convert your number to a human readable string
String output = myFormatter.format(22.99999f);
System.out.println(output); // Prints $23.00
See this page for details on the various patterns https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

How to remove the E7 when a number is too high? [duplicate]

Here is my simple code
#Override
public void onClick(View v) {
try {
double price = Double.parseDouble(ePrice.getText().toString());
double percent = Double.parseDouble(ePercent.getText().toString());
double priceValue = price * percent/100.0f;
double percentValue = price - priceValue;
moneyToGet.setText(String.valueOf(priceValue));
moneyToPay.setText(String.valueOf(percentValue));
moneyToGet.setText("" + priceValue);
moneyToPay.setText("" + percentValue);
// catch
} catch (NumberFormatException ex) {
// write a message to users
moneyToGet.setText("");
}
}
});
This is a simple code for Percentage Calculator.
What I want is to avoid the Scientific Notation in my Calculator cause I don't want to explain to user what is Scientific Notation.
For example if I want to calculate 100,000,000 and cut 50% of it, it Should give me 50,000,000 which is giving me 5.0E7 And in my case this doesn't make any sense to the user. And of course I know both results are correct.
Thanks in Advance.
Check answer here. You can write
moneyToGet.setText(String.format("%.0f", priceValue));
You can try this DecimalFormat
DecimalFormat decimalFormatter = new DecimalFormat("############");
number.setText(decimalFormatter.format(Double.parseDouble(result)));
I would suggest using BigDecimals instead of doubles. That way you will have a more precise control over your calculation precision. Also you can get a non-scientific String using BigDecimal.toPlainString().
DecimalFormat decimalFormatter = new DecimalFormat("##.############");
decimalFormatter.setMinimumFractionDigits(2);
decimalFormatter.setMaximumFractionDigits(15);
This option will help you ##.## suffix 0 before decimal, otherwise output will be .000
btc.setText(decimalFormatter.format(btcval));
use this for displaying content
Use NumberFormater like
NumberFormat myformatter = new DecimalFormat("########");
String result = myformatter.format(yourValue);

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.
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));

Format Price in 0.00 format in android using edittext

I am trying to mask a price value so that it is always in 0.00 format. Here is my code
float temp = 0;
DecimalFormat mDecimalFormat = new DecimalFormat("###.00");
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString()!=null)
{
mMasEditText.removeTextChangedListener(this);
temp = Float.parseFloat(s.toString());
mMasEditText.setText(""+mDecimalFormat.format(addNumber(temp)));
mMasEditText.setSelection(start+1);
mMasEditText.addTextChangedListener(this);
}
}
public float addNumber(float numTemp){
float result=0.00f;
result = numTemp + result;
return result;
}
But when I am pressing decimal, I want the cursor to go to one more step. But I am not able to get the dot callback. Also when I am pressing the back button, to remove digits, I get an index out of bound exception. Can anyone tell me how to get the back button and dot button callback before onTextChanged listener?
Recommended way of formatting currency and prices:
Locale loc = Locale.getDefault();
NumberFormat nf = NumberFormat.getCurrencyInstance(loc);
nf.setCurrency(Currency.getInstance(loc));
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
System.out.println(nf.format(23.5634));
System.out.println(nf.format(0.5));
use String.format
String.format("$%.2f", result);
or
Strint text = String.format("$%.2f", addNumber(temp));
mMasEditText.setText(text)

Categories