how can I input decimals in to input field - android - java

I'm just starting to play around with android app.
I have an text field to input numbers but somehow I can only type in regular integers without decimals.
any idea what I can do so I can input decimals too?
This is what I have..
public void onClick(View arg0) {
EditText edit = (EditText)findViewById(R.id.editText1);
TextView text = (TextView)findViewById(R.id.textView1);
String input = edit.getText().toString();
float num = 0;
try {
num = Integer.parseInt(input);
} catch (NumberFormatException e) {
input = "0";
}
double newNum = num * 1.12;
DecimalFormat df = new DecimalFormat("###.##");
text.setText(input + " * 12% = " + df.format(newNum));

Add the following attribute to your EditText in xml:
android:inputType="numberDecimal"
This will inform the keyboard to enter decimals.

if you want to get decimal number keyboard you should add inputType with value numberDecimal in EditText xml file:
android:inputType="numberDecimal"
And if you want to use comma and dot also, you should add digits also in EditText xml:
android:digits="0123456789.,"
and when you get that result in Java, don't forget to replace dot with comma because Double and Float can only parse dot separated text:
String test = "12,34";
String changed = test.replace(",",".")
float value = Float.parseFloat(changed)

Related

Simple math in a String using java

This is what I have :
final EditText Pikkus = (EditText)findViewById(R.id.editText);
final EditText Laius = (EditText)findViewById(R.id.editText3);
final TextView pindala1 = (TextView)findViewById(R.id.editText2);
final TextView ymbermoot1 = (TextView)findViewById(R.id.textView5);
ImageButton button = (ImageButton)findViewById(R.id.teisenda);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pindala2 = "" + Integer.parseInt(Pikkus.getText().toString()) * Integer.parseInt(Laius.getText().toString());
pindala1.setText(pindala2);
String ymbermoot2 = "" + Integer.parseInt(Pikkus.getText().toString()) + Integer.parseInt(Laius.getText().toString())
ymbermoot1.setText(ymbermoot2);
}
});
But the
String ymbermoot2 = ""
+ Integer.parseInt(Pikkus.getText().toString())
+ Integer.parseInt(Laius.getText().toString());
ymbermoot1.setText(ymbermoot2);
part doesn't work like its supposed to. Instead of adding up the values, it simply types them together. Example: integer Pikkus is 26, Laius is 23. The value should end up being 49, but my code somehow makes it to up to be 2623. Where's the mistake in the code?
Try something like this.
String ymbermoot2 = Integer.toString(Integer.parseInt(Pikkus.getText().toString()) + Integer.parseInt(Laius.getText().toString()));
That's what happens when you try to write as little lines as possible, and it's so wrong. Of course - number of lines determines good code but not always. So I would split it into few lines:
int someNumber = Integer.parseInt(Pikkus.getText().toString());
int someOtherNumber = Integer.parseInt(Laius.getText().toString());
String pindala2 = String.valueOf(someNumber * someOtherNumber);
Try the following code:
String ymbermoot2 = "" + (Integer.parseInt(Pikkus.getText().toString())
+ Integer.parseInt(Laius.getText().toString()))
It will help.
String pindala2 = "" + (Integer.parseInt(Pikkus.getText().toString()) * Integer.parseInt(Laius.getText().toString()));
int value = Integer.parseInt(Pikkus.getText().toString()) + Integer.parseInt(Laius.getText().toString())
This is because you are concatenating strings instead of adding or multiplying them up because you cannot make arithmetic operations on strings . Try following code :
String pindala2 = ""+Integer.toString((Integer.parseInt(Pikkus.getText().toString()) * Integer.parseInt(Laius.getText().toString())));
Here we are first we multiply two integers and then converting it to String.

EditText does not take the value if entered a float value

Here's my code
if(numberbyUser.getText().toString().equals(""))
{
//Toast.makeText(getApplicationContext(), "Please Enter a Number", Toast.LENGTH_SHORT).show();
message = "Please Enter a Number !!";
DialogFunction();
}
If I enter a value for eg: 1.5 code goes into the above loop. But for values which are not decimal code just works fine.
Can somebody please tell me whats going wrong?
I suggest that make the EditText field as a text android:inputType="text" then do the conversion. Try this:
String sNumberByUser = numberbyUser.getText().toString();
Double number = 0.0;
try{
if(!sNumberByUser.equals("")){
// This will accept decimal and non-decimal number
number = Double.parseDouble(sNumberByUser);
//do your process here
}else{
throw new NumberFormatException();
}
//Catch if not a number.
}catch(NumberFormatException nfe){
message = "Please Enter a Number !!";
DialogFunction();
}
can you post the XML for the your edittext...it may be possible that you set the
inputType="number" instead of "decimal..."
<EditText
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="decimal" />
change inputType attribute to "decimal"
if(numberbyUser.getText().length() > 0) {
String numberString = numberByUser.getText().toString();
Double number = Double.parseDouble(numberString);
//To operation with entered number.
} else {
message = "Please enter number.";
DialogFunction();
}
And in your layout add android:inputType = "numberDecimal"
Hope this will help you.

Java Double Currency Format to 3 Places [duplicate]

This question already has answers here:
How to format decimals in a currency format?
(22 answers)
Closed 8 years ago.
I have a Java Android app that deals with tips. When I take in the double of bill amount and tip percent, I parse them to to strings to display later.
How can I easily format the doubles to make the currency more readable at the end? Instead of looking like $1.0 it would be $1.00.
The code I have mentioned is:
final EditText amt = (EditText) findViewById(R.id.bill_amt);
final EditText tip = (EditText) findViewById(R.id.bill_percent);
final TextView result = (TextView) findViewById(R.id.res);
final TextView total = (TextView) findViewById(R.id.total);
double amount = Double.parseDouble(amt.getText().toString());
double tip_per = Double.parseDouble(tip.getText().toString());
double tip_cal = (amount * tip_per) / 100;
double totalcost = amount + tip_cal;
result.setText("Tip Amount : " + " $ " + Double.toString(tip_cal));
total.setText("Total Cost: " + " $ " + totalcost);
I would like result and total at the end to be the outputs that are nicely formatted doubles to 3 places. Thanks for any advice you can give.
you can user DecimalFormat to do the job for you
ex
double x = 1.0;
DecimalFormat decimalFormat = new DecimalFormat("$#0.00");
String text = decimalFormat.format(x);
[enter link description here][1]
http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

Java: 2 runtime errors I can't figure out

I am working on a homework assignment, and I am going a little "above and beyond" what is called for by the assignment. I am getting a run-time error in my code, and can not for the life of me figure out what it is that I have done wrong.
Here is the assignment:
Write a program that displays a simulated paycheck. The program should ask the user to enter the date, the payee’s name, and the amount of the check. It should then display a simulated check with the dollar amount spelled out.
Here is my code:
CheckWriter:
/* CheckWriter.java */
// Imported Dependencies
import java.util.InputMismatchException;
import java.util.Scanner;
public class CheckWriter {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
// Try to get the name
String name = "";
NameValidator validateName = new NameValidator();
while (validateName.validate(name) == false) {
System.out.println("Enter the name: ");
name = keyboard.nextLine();
if (validateName.validate(name) == false) {
System.out.println("Not a valid name.");
}
}
// Get the date
String date = "";
DateValidator validateDate = new DateValidator();
while (!validateDate.validate(date)) {
System.out.println("Enter the date (dd/mm/yyyy): ");
date = keyboard.nextLine();
if (!validateDate.validate(date)) {
System.out.println("Not a valid date.");
}
}
// Try to get the amount of the check
String checkAmount = "";
CurrencyValidator validateCurrency = new CurrencyValidator();
while (!validateCurrency.validate(checkAmount)) {
System.out.print("Enter the Check Amount (XX.XX): $");
checkAmount = keyboard.nextLine();
if (!validateCurrency.validate(checkAmount)) {
System.out.println("Not a valid check amount.");
}
}
String checkWords = checkToWords(checkAmount); // ERROR! (48)
System.out
.println("------------------------------------------------------\n"
+ "Date: "
+ date
+ "\n"
+ "Pay to the Order of: "
+ name
+ " $"
+ checkAmount
+ "\n"
+ checkWords
+ "\n"
+ "------------------------------------------------------\n");
}
private static String checkToWords(String checkAmount) {
/**
* Here I will use the string.split() method to separate out
* the integer and decimal portions of the checkAmount.
*/
String delimiter = "\\.\\$";
/* Remove any commas from checkAmount */
checkAmount.replace(",", "");
/* Split the checkAmount string into an array */
String[] splitAmount = checkAmount.split(delimiter);
/* Convert the integer portion of checkAmount to words */
NumberToWords intToWord = new NumberToWords();
long intPortion = Long.parseLong(splitAmount[0]); // ERROR! (84)
intToWord.convert(intPortion);
String intAmount = intToWord.getString() + " dollars";
/* Convert the decimal portion of checkAmount to words */
String decAmount = "";
long decPortion = Long.parseLong(splitAmount[1]);
if (decPortion != 0) {
NumberToWords decToWord = new NumberToWords();
decToWord.convert(Long.parseLong(splitAmount[1]));
decAmount = " and " + decToWord.getString() + " cents.";
}
return (intAmount + decAmount);
}
}
Note that I am using external class files to handle validation of the name, date, currency, and conversion from numbers to words. These class files all work as intended.
The error I am getting is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at CheckWriter.checkToWords(CheckWriter.java:82)
at CheckWriter.main(CheckWriter.java:46)
I have commented the lines in my code that are causing the errors that I am experiencing.
Could someone please assist me in figuring where my code is going wrong? I can include the other class files if you feel that it would be needed.
EDIT: When I run the code, it asks for the name and date. Before asking for the check amount is when it throws the error.
EDIT 2: A huge thank you to cotton.m! Thanks to his advice, I have changed the while statements to look like this:
while(!validateDate.validate(date) && date == "")
This has now fixed my issue. It would appear that when validating data with a regex expression, an empty string will return true.
The String you are trying to parse in an empty length string.
My suggestion would be to
1) Check the value of checkAmount at the start of checkToWords - if it is blank there's your problem
2) Don't do that split. Just replace the $ like you did the , (I think this is your real problem)
Also you are going to have another issue in that 10000.00 is not a long. I see you are splitting out the . but is that really what you want?
It is NumberFormatException, the value in checkAmount (method parameter) is not a valid Number.
You need to set checkAmount=checkAmount.replace(",", "");
Otherwise checkAmount will still have , inside and causes NumberFormatExcpetion.
Your issue is with your delimiter regex, currently you are using \.\$ which will split on a literal . followed by a literal $. I'm assuming that what you are actually intending to do is to split on either a . or a $, so change your delimiter to one of the following:
String delimiter = "\\.|\\$"
or
String delimiter = "[\\.\\$]"
As your code is now, checkAmount.split(delimiter) is not actually successfully splitting the string anywhere, so Long.parseLong(splitAmount[0]) is equivalent to Long.parseLong(checkAmount).
It should be:
String delimiter = "[\\.\\$]";
and then you have to check that splitWord[i] is not empty.

Convert String with Dot or Comma to Float Number

I always like input in my function to get numbers that range from 0.1 to 999.9 (the decimal part is always separated by '.', if there is no decimal then there is no '.' for example 9 or 7 .
How do I convert this String to float value regardless of localization (some countries use ',' to separate decimal part of number. I always get it with the '.')? Does this depend on local computer settings?
The Float.parseFloat() method is not locale-dependent. It expects a dot as decimal separator. If the decimal separator in your input is always dot, you can use this safely.
The NumberFormat class provides locale-aware parse and format should you need to adapt for different locales.
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
DecimalFormat format = new DecimalFormat("0.#");
format.setDecimalFormatSymbols(symbols);
float f = format.parse(str).floatValue();
valueStr = valueStr.replace(',', '.');
return new Float(valueStr);
Done
See java.text.NumberFormat and DecimalFormat:
NumberFormat nf = new DecimalFormat ("990.0");
double d = nf.parse (text);
What about this:
Float floatFromStringOrZero(String s){
Float val = Float.valueOf(0);
try{
val = Float.valueOf(s);
} catch(NumberFormatException ex){
DecimalFormat df = new DecimalFormat();
Number n = null;
try{
n = df.parse(s);
} catch(ParseException ex2){
}
if(n != null)
val = n.floatValue();
}
return val;
}
You can use the placeholder %s-String for any primitive type.
float x = 3.15f, y = 1.2345f;
System.out.printf("%.4s and %.5s", x, y);
Output: 3.15 and 1.234
%s is always english formatting regardless of localization.
If you want a specif local formatting, you could also do:
import java.util.Locale;
float x = 3.15f, y = 1.2345f;
System.out.printf(Locale.GERMAN, "%.2f and %.4f", x, y);
Output: 3,15 and 1,2345
I hope this piece of code may help you.
public static Float getDigit(String quote){
char decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
String regex = "[^0-9" + decimalSeparator + "]";
String valueOnlyDigit = quote.replaceAll(regex, "");
if (String.valueOf(decimalSeparator).equals(",")) {
valueOnlyDigit = valueOnlyDigit.replace(",", ".");
//Log.i("debinf purcadap", "substituted comma by dot");
}
try {
return Float.parseFloat(valueOnlyDigit);
} catch (ArithmeticException | NumberFormatException e) {
//Log.i("debinf purcadap", "Error in getMoneyAsDecimal", e);
return null;
}
}

Categories