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
Related
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.
I have a simple screen with two EditText Boxes and 1 button. I want users to be able to enter various integers into the boxes and the program will perform different operations based on the specific number entered into the box. I'm trying to have them only enter one number at a time but the code wont seem to execute unless both boxes have something in them. And I'm having the if statements check for nulls on the respective boxes before executing to determine which piece of code to execute.
public void button(View view) {
double x, y;
EditText freq1 = findViewById(R.id.freq1);
EditText freq2 = findViewById(R.id.freq2);
TextView str1 = findViewById(R.id.freqanswer);
TextView str2 = findViewById(R.id.injVolt);
TextView error1 = findViewById(R.id.error1);
String strf1, strf2;
strf1 = freq1.getText().toString();
strf2 = freq2.getText().toString();
try {
f1 = Double.parseDouble(strf1);
f2 = Double.parseDouble(strf2);
if ((f1 >= 225) & (f1 <= 312) & (strf1.isEmpty())) {
x = f1 + 20.6;
y = x / 4;
str1.setText(String.format("%.3f", y));
}
}
catch (Exception e){
error1.setText("splat");
}
finally {
InputMethodManager input = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
I included only 1 formula for the sake of brevity, but I'm going to be putting about 6 if statements, checking for number ranges and nulls on this button and I just need it to run with one box being empty. I know the formula works by having play with various outputs, it just won't run with the strf1.isEmpty(). Something has to be in that second box for the formula to execute.
Would appreciate any help
I think you should check before assigning:
if(strf1.isEmpty()){strf1="0";} //if assuming zero does not change the formula's output
if(strf2.isEmpty()){strf2="0";}
f1 = Double.parseDouble(strf1);
f2 = Double.parseDouble(strf2);
this way you are assured of a default value.
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);
So, I am messing around with java/android programming and right now I am trying to make a really basic calculator. I am hung up on this issue though. This is the code I have right now for getting the number thats in the textview and making it an int
CharSequence value1 = getText(R.id.textView);
int num1 = Integer.parseInt(value1.toString());
And from what I can tell it is the second line that is causing the error, but im not sure why it is doing that. It is compiling fine, but when it tries to run this part of the program it crashes my app. And the only thing thats in the textview is numbers
Any advice?
I can also provide more of my code if necessary
You can read on the usage of TextView.
How to declare it:
TextView tv;
Initialize it:
tv = (TextView) findViewById(R.id.textView);
or:
tv = new TextView(MyActivity.this);
or, if you are inflating a layout,
tv = (TextView) inflatedView.findViewById(R.id.textView);
To set a string to tv, use tv.setText(some_string) or tv.setText("this_string"). If you need to set an integer value, use tv.setText("" + 5) as setText() is an overloaded method that can handle string and int arguments.
To get a value from tv use tv.getText().
Always check if the parser can handle the possible values that textView.getText().toString() can supply. A NumberFormatException is thrown if you try to parse an empty string(""). Or, if you try to parse ..
String tvValue = tv.getText().toString();
if (!tvValue.equals("") && !tvValue.equals(......)) {
int num1 = Integer.parseInt(tvValue);
}
TextView tv = (TextView)findviewbyID(R.id.textView);
int num = Integer.valueOf(tv.getText().toString());
Here is the kotlin version :
var value = textview.text.toString().toIntOrNull() ?: 0
TextView tv = (TextView)findviewbyID(R.id.textView);
String text = tv.getText().toString();
int n;
if(text.matches("\\d+")) //check if only digits. Could also be text.matches("[0-9]+")
{
n = Integer.parseInt(text);
}
else
{
System.out.println("not a valid number");
}
this code actually works better:
//this code to increment the value in the text view by 1
TextView quantityTextView = (TextView)findViewById(R.id.quantity_text_view);
CharSequence v1=quantityTextView.getText();
int q=Integer.parseInt(v1.toString());
q+=1;
quantityTextView.setText(q +"");
//I hope u like this
I am having an issue with my program, my textveiw will not display any decimals, heres the break down on whats happeneing. The user enters a number in a textEdit (Also how do i make the textedit only accept numbers AND a decimal point?) that number gets converted to a int, sent to my second activity, diveded by 3600, then displayed in a textveiw box. The issue is that when that number is displayed it has no decimal value, for example if its less than 1 it will not display anything, how can i go about fixing this? i need it to at least go to the 1000th place.
Here is my code one activity1:
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, PayTracker.class);
// Gather text from text boxes
EditText editText = (EditText) findViewById(R.id.hourly_wage);
//Create String from text
String message1 = editText.getText().toString();
//Convert String to Int
int HW = 0;
try{
HW = Integer.valueOf(message1);
}
catch(NumberFormatException nfe){
//do something else here
//for e.g. initializing default values to your int variables
}
// Send Integers to PayTracker.java
intent.putExtra(MESSAGE_HW, HW);
// start new activity
startActivity(intent);
And then this is activity2 where the number needs to be displayed:
public void sendMessage(View view) {
// Receive messages from options page
Intent intent = getIntent();
int HW = intent.getIntExtra(Options.MESSAGE_HW, 0);
// Calculate pay per second
int PPS = 0;
PPS = (HW/3600);
// set textView
TextView textView = (TextView) this.findViewById(R.id.yourpay);
textView.setText(String.valueOf(PPS));
}
Any help would be appreciated! thanks!
Use doubles or floats. From what I see, everything should work except that you forgot that 5 divided by 2 as int is 2, and not 2.5.
so do as gtumca said and use doubles; longs are just bigger ints.
in other words...
activity1
try{
HW = Double.valueOf(message1);
}
activity 2
//double HW = intent.getIntExtra(Options.MESSAGE_HW, 0);
double HW = intent.getDoubleExtra(Options.MESSAGE_HW, 0);
// pay is rarely a round number
double PPS = HW / 3600;
that number gets converted to a int
Integers dont have decimals :)
As to the EditText only accepting numbers:
EditText, inputType values (xml)
Set one of those types to your EditText in the Layout xml like:
android:inputType="number"
You are using int as data type so you are getting int values only
double PPS = 0;
^^^^^^
instead of
int PPS = 0;
You shouldn't use float or double to keep numbers with such big precision. Float and double cannot represent decimal fractions exactly due to their internal representations. Please, check BigDecimal if you want 1000-digit precission(or more).