Android Studio - DecimalFormat (java.text) - Not working properly - java

So, I have this following code to make a simple temperature app converter in Android Studio 4.0.1:
bt_converter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double tempC = Double.parseDouble(et_tempC.getText().toString());
DecimalFormat arredondar = new DecimalFormat("#.##");
double tempF = Double.parseDouble(arredondar.format(tempC * 1.8 + 32));
tv_tempF.setText(String.valueOf(tempF));
}
The problem is that when I run the app it crashes due to this statement:
DecimalFormat arredondar = new DecimalFormat("#.##");
And the same for:
DecimalFormat arredondar = new DecimalFormat("0.00");
In fact it crashes with every pattern started by "0" and involving point "."
I've tried to switch it to:
DecimalFormat arredondar = new DecimalFormat("#,##");
And it actually works but it is not showing two decimal places as intended, and no matter what tempC value I put in, the output is always some number point zero (xx.0).
For example:
for tempC = 10.11111111
it shows tempF = 50.0
When it should give me 50.19 or 50.2 instead.
I've reinstalled the app and cleaned the project, and even changed my windows 10 region settings (with regards to decimal symbols), but it still remains the same.
But please let me know if you need more details.

So, I came to a solution, and it works as intended.
I just changed the three last lines of code:
Before
DecimalFormat arredondar = new DecimalFormat("#.##");
double tempF = Double.parseDouble(arredondar.format(tempC * 1.8 + 32));
tv_tempF.setText(String.valueOf(tempF));
After:
DecimalFormat arredondar = new DecimalFormat("0.00");
double tempF = tempC * 1.8 + 32;
tv_tempF.setText(arredondar.format(tempF));
Apparently there is some king of error/incompatibility. But, I realised that I was converting tempF from String to Double with the second line in the before code, and then convert it back again to String with the third one.
So I simply put the tempF directly in the output with a String format, after having calculated it with no convertion:
double tempF = tempC * 1.8 + 32;
tv_tempF.setText(arredondar.format(tempF));
And I've changed the pattern from "#.##" to "0.00" to make sure that I get two decimal places everytime.

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 do I format a double into a string (with only two decimal places)?

I am creating an app for Android using Android Studio. I have a block of code that collects some strings, converts them into doubles, puts them into equations, and then puts the answers into TextViews with only two decimal places.
double weightDouble = Double.parseDouble(weightTextField.getText().toString());
double dehydrationDouble = Double.parseDouble(dehydrationTextField.getText().toString());
double lossesDouble = Double.parseDouble(lossesTextField.getText().toString());
double factorDouble = Double.parseDouble(factorTextField.getText().toString());
double fluidStepOne = (((Math.sqrt(Math.sqrt((weightDouble * weightDouble * weightDouble))))) * 70) * factorDouble;
double fluidStepTwo = fluidStepOne + (weightDouble * dehydrationDouble * 10);
double fluid24Hours = fluidStepTwo + lossesDouble;
double fluidHourInt = fluid24Hours / 24;
fluidResultLabel.setText(String.format(Locale.US, "%.2f", Double.toString(fluid24Hours)));
fluidPerHourResultLabel.setText(String.format(Locale.US, "%.2f", Double.toString(fluidHourInt)));
However, when this block of code is run, the app crashes, and Android Studio says this-
java.util.IllegalFormatConversionException: %f can't format java.lang.String arguments
at java.util.Formatter.badArgumentType(Formatter.java:1489)
at java.util.Formatter.transformFromFloat(Formatter.java:2038)
at java.util.Formatter.transform(Formatter.java:1465)
at java.util.Formatter.doFormat(Formatter.java:1081)
at java.util.Formatter.format(Formatter.java:1042)
at java.util.Formatter.format(Formatter.java:1011)
at java.lang.String.format(String.java:1554)
at com.georgeberdovskiy.fluidtherapy.MainActivity$1.onClick(MainActivity.java:82)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5444)
at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:746)
My questions are-
How do I fix this problem? (how do I propery format a double into a two-decimal string)
Is there anything else I can change to make my code shorter and less prone to bugs?
Thanks!- George
PS- This question is not a duplicate because the answers to questions the same as mine didn't work, and my circumstances are different.
Replace Double.toString() with only double value like below:
String formattedNumber = String.format(Locale.US, "%.2f", fluid24Hours);
Or from Java 8 use formatter like below:
NumberFormat formatter = DecimalFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
String formattedNumber = formatter.format(fluid24Hours);
double d1 = 123456.78;
double d2 = 567890;
Locale fmtLocale = Locale.getDefault(Category.FORMAT);
NumberFormat formatter = NumberFormat.getInstance(fmtLocale);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
System.out.println(formatter.format(d1));
System.out.println(formatter.format(d2));
System.out.println(fmtLocale.toLanguageTag());
Use this code
fluidPerHourResultLabel.setText(new DecimalFormat("##.##").format(fluidHourInt));
Please check the link
Show only two digit after decimal
Down cast Original double value into string suppose say aString.
then use
newTrimmedString = aString.substring(0, Math.min(AString.length(), 5)); <---- 5 Represents total no. of character u wish to print/save upto.
From java 8, this is the way:
https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

JavaFX Label double precision

Currently, I'm practicing my JavaFX skills. Mostly, I'm trying to solve problem by myself, but this time it's out of my mind.
I decided to create a unit converter. Everything was OK until I wanted to get my calculations inside Labels Mine code works good, but I'm not happy to see 10 or more decimals when I input numbers like 155.54 etc.
Here's the code:
value = input.getText().toString();
dValue = Double.parseDouble(value);
public void temperatureHandler() {
if (cBox.getValue() == "Celsius (C)") {
celsiusOutput.setText(Double.toString(dValue));
fahrenheitOutput.setText(Double.toString((dValue * 1.8) + 32));
kelvinOutput.setText(Double.toString(dValue + 273.15));
}
else if (cBox.getValue() == "Fahrenheit (F)") {
celsiusOutput.setText(Double.toString((dValue - 32) / 1.8));
fahrenheitOutput.setText(Double.toString(dValue));
kelvinOutput.setText(Double.toString((dValue + 459.67) * 5/9));
}
else if (cBox.getValue() == "Kelvin (K)") {
celsiusOutput.setText(Double.toString(dValue - 273.15));
fahrenheitOutput.setText(Double.toString((dValue * 1.8) - 459.67));
kelvinOutput.setText(Double.toString(dValue));
}
}
I have some experience in using String formats, StringBuilders etc. But I have no idea how can I set precision inside Label. I want to set it to 2 decimals.
Thanks you in advance.
Use a decimal format to format / truncate your double to 2 decimal places..
Example
DecimalFormat df = new DecimalFormat("#.00");
df.format(myDouble);
in your case
DecimalFormat df = new DecimalFormat("#.00");
celsiusOutput.setText(df.format((dValue - 32) / 1.8));

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

Categories