In my app, i want to be able to format numbers to string (with commas) in a TextView e.g 123456.000 to 123,456.000. But the problem is when i type zero (0) as the last number after the decimal point, it shows nothing until i type another number. For example, if i type 123456.000, i get 123,456. The zeros doesn't show until i type another number like "1" then i get 123,456.0001. Please how do i make zeros show as last number after decimal point? Below are some sample codes.
I apologise for the clumsiness of the code. I manually typed it with my phone.
TextView txtView;
boolean NumberClicked = false;
String number = "";
// format pattern
DecimalFormat formatter = new DecimalFormat("#,###.#########");
// input dot (decimal point)
dot.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
if (!txtView.getText.toString.contains(".") {
input(".");}}});
// input zero (0)
zero.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
input("0");
}});
// input one (1)
one.setOnClickListener (new
View.OnClickLstener() {
public void onClick(View view) {
input("1");}});
// input method
public void input (String view) {
if (!numberClicked) {
number = view;
numberClicked = true;
} else {
number = number + view;
}
// print the entered numbers to
//the TextView after formatting
if (!number.endsWith(".")) { txtView.setText(formatter.format(Double.parseDouble(number)));}}
enter code here
You may try this code snippet:
DecimalFormat df = new DecimalFormat("#,##0.0#");
df.setMinimumFractionDigits(3);
String value = df.format(123456.000);
Output: 123,456.000
For more info pls click here.
Try with:
String.format("%,.03f", 123456.000)
Related
I am building a calculator app and everything is working properly but I don't know the code for backspace.
public class MainActivity extends AppCompatActivity {
// UI Elements
private TextView num_input;
private TextView num_input;
private ImageButton num_backspace;
private float input, input2 ;
boolean Addition, Subtract, Multiplication, Division, mRemainder, decimal, add_sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
num_input = findViewById(R.id.num_input);
num_output = findViewById(R.id.num_output);
num_backspace = findViewById(R.id.num_backspace);
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
//TODO: the backslash code goes here.
});
}
}
I tried doing this👇🏻
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
input = Float.parseFloat(num_input.getText() + "");
String sample_input = Float.toString(input);
sample_input = sample_input.substring(0,sample_input.length() - 1);
});
Some help would be great!
thanks in advance
It's better to store input as a String, not float. Because before you start doing mathematical calculations it's just a String input, and "backspace" means basically removing one character, it's not a mathematical operation. So, provided input is a String, backspace code will be:
input = input(0, input.length() - 1);
num_input.setText(input);
And before doing calculations convert your String input into float via
float operand = Float.parseFloat(input);
Put this code inside your setOnClickListener
String value = num_input.getText().toString();
if (value != null && value.length() > 0 ) {
value = value.substring(0, value.length() - 1);
}
num_input.setText(value);
How this is usually done is getting the current value (entered number) in the TextView, remove the last character from the string and writing it back to the TextView.
i have problem with my simple calculate with only multiplication from the edittext where the user input the numbers. When user click result button, numbers that user input from edittext do multiplication and show result in textview.
input = (EditText)findViewById(R.id.input);
output1 = (TextView)findViewById(R.id.output_one);
output2 = (TextView)findViewById(R.id.output_two);
output3 = (TextView)findViewById(R.id.output_three);
result = (Button)findViewById(R.id.result);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
output1.setText(input.getText()*"2");
output2.setText(input.getText()*"3");
output3.setText(input.getText()*"4");
}
}
(input.getText()*"") showing red underline. It said 'Operator * cannot be applied to android.text.editable, java.lang.String' .
Anyone can fill my code? I m beginners :)
String can not be calculated, you need to convert into numbers in the operation, you can try:
Integer.valueOf ("")
make sure the user inputs a number, use
android:inputType="number"
in the EditText attributes.
input = (EditText)findViewById(R.id.input);
output1 = (TextView)findViewById(R.id.output_one);
output2 = (TextView)findViewById(R.id.output_two);
output3 = (TextView)findViewById(R.id.output_three);
result = (Button)findViewById(R.id.result);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// storing the EditText value in a variable.
// do it in the onClick method only.
int inputVal = Integer.parseInt(input.getText().toString());
output1.setText(inputVal * 2);
output2.setText(inputVal * 3);
output3.setText(inputVal * 4);
}
}
input => EditText
When you use input.getText() you get object of Editable class.
If you want to get its value, you have to convert Editable to String, using input.getText().toString().
Now you want to multiply the value, So you have to convert String to Integer(or relevant dataType), by Integer.parseInt(input.getText().toString()) and then multiply with your value.
Now you want to assign this updated value to TextView, use String.valueOf().
So finally your code should be:
int inputVal = Integer.parseInt(input.getText().toString());
output1.setText(String.valueOf(inputVal * 2));
output2.setText(String.valueOf(inputVal * 3));
output3.setText(String.valueOf(inputVal * 4));
use this
output1.setText(Integer.valueOf(input.getText().trim())*Integer.valueOf("2"));
output2.setText(Integer.valueOf(input.getText().trim())*Integer.valueOf("3"));
output3.setText(Integer.valueOf(input.getText().trim())*Integer.valueOf("4"));
You are trying to multiply strings. You should transform the string into numbers before multipling them.
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
int inputInt = Integer.parseInt(input.getText());
int inputInt_times2 = 2*inputInt;
int inputInt_times3 = 3*inputInt;
int inputInt_times4 = 4*inputInt;
output1.setText(inputInt_times2+"");
output2.setText(inputInt_times3+"");
output3.setText(inputInt_times4+"");
}catch(Exception e){
//handle the exception here
}
}
}
the (+"") that I added in the setText was to transform the int to String again.
I am creating a calculator app in android. The issue is how can I check for existence of two decimals in a single numeric value . Currently my calculator allows inputs such as 1.2.3 which is illegal . It must allow a decimal if an operator has been used. Eg 1.1+2.2 is legal but 1.1.1+2.2 isn't.
Here is my code for decimal handling:
public class TrialCalculator extends AppCompatActivity implements Button.OnClickListener {
Button btn1, btn2, btnBack, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnPlus, btnMinus, btnMul, btnDiv, btnEquals, btnClear, btnDecimal, btnPercent;
EditText calcResult;
double number = 0;
private char opcode = '1';
private void handleDecimal() {
if (opcode == 0) clear();
if (calcResult.getText() == null) {
calcResult.setText("0.");
calcResult.setSelection(2);
} else {
String txt = calcResult.getText().toString();
if (txt.lastIndexOf(".")<txt.length()-1) {
calcResult.append(".");
}
}
}
}
I am calling the buttonDot from onClick Method.
One solution is to have a flag which keeps track of the decimal:
class MyCalculator {
private hasDecimal = false;
// ...
}
Set this flag to true the first time that the user types a decimal. Then check the flag to see if a decimal has been previously typed.
Of course, this only works if you are responding to each key press directly rather than getting the entire input from a EditText after the user has typed the entire number.
You can use regex with matches function
\\d* mean match zero or more digits
(\\.\\d+)? match a . followed by one or more digits , ? mean matches between zero or one times of given group
Regex Demo : note with matches function in java, we don't need ^ start and $ ending anchors
Code
if (txt.matches("\\d*(\\.\\d+)?")) {
// number has one decimal
}
else{
// number has more than one decimal
}
Note: if you don't want to allow values like .5 then use \\d+ instead of \\d* as
\\d+(\\.\\d+)?
As suggested by #Code-Apprentice , if you want to accept values like 4343. etc
you can use
\\d*(\\.\\d*)?
Using text watcher
calcResult.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void afterTextChanged(Editable s) {
boolean flag = s.toString().matches("\\d*(\\.\\d*)?");
if(!flag){
// calcResult.setError...
// you display a toast
}
}
});
Update : To match multiple values with operators , you can use
(\\d*(\\.\\d*)?([+\\-*%\\]|$))*
RegEx demo
Test Cases
String pat="(\\d*(\\.\\d*)?([+\\-*%\\]|$))*";
System.out.println("4.5-3.3+3.4".matches(pat));
System.out.println(".5".matches(pat));
System.out.println("4".matches(pat));
System.out.println("4.5.5-4.4".matches(pat));
System.out.println("4.44.5+4.4.4".matches(pat));
System.out.println("4.".matches(pat));
Output :
true
true
true
false
false
true
lastIndexOf returns -1 if the character is not found in the string. So your condition txt.lastIndexOf(".")<txt.length()-1 is always true. You could change it to
txt.lastIndexOf(".") == -1
To check for existence of two decimals in a single no then split the string by decimal.
for e.g.,
String txt = calcResult.getText().toString();
String[] decimals = txt.split("\\.");
if(decimals.length > 2) {
// txt contains more than 1 decimal.
// Your logic ..
}
I would like to change a TextView as a user adds things to a cart. The initial value is 0.00 and as the user adds items, this is added to the value. I have an AlertDialog that pops up when clicking a button that allows the user to choose an item.
My issue is a java.lang.StringToReal.invalidReal error. I think that I may not be getting the value of the TextVeiw properly but am not totally sure.
Thanks to anyone looking at this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.pickItem);
builder.setItems(R.array.items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
CartItems ci = new CartItems();
ci.setItem(which);
ci.setPrice(which);
cart.add(ci);
totalPriceTV = (TextView)findViewById(R.id.textView2);
double totalPrice = Double.parseDouble(totalPriceTV.toString());
totalPrice += ci.getPrice();
String newTotal = new Double(totalPrice).toString();
totalPriceTV.setText(newTotal);
}
});
builder.create();
builder.show();
}
});
}
In this line
double totalPrice = Double.parseDouble(totalPriceTV.toString());
Change totalPriceTV.toString() to totalPriceTV.getText().toString() and try again.
In order to change the text of a TextView in Android just use the ordinary geters and setters:
TextView.getText();
TextView.setText("text");
Since you deal with numbers i suggest you to use DecimalFormat when parsing a double to string. You can easily define the format of the number (i.e the number of digits after comma or the separator characters)
DecimalFormat df = new DecimalFormat("###,###.00");
String price = df.parse(someDouble);
textView.setText(price);
For these numbers: 234123.2341234 12.341123 the DecimalFormat would give you the following result:
234,123.23 and 12.34
Taken from page: http://developer.android.com/reference/android/view/View.html#toString()
Added in API level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
getClass().getName() + '#' + Integer.toHexString(hashCode())
As a result you should use getText();
ie:
totalPriceTV.getText()
Just use totalPriceTV.setText(""+totalPrice);
or
totalPriceTV.setText(String.valueOf(totalPrice));
Making a simple app for my android.
in my xml interface there is a text box in which the user will input a number (for example: 10). the id of this text box is "input1"
how do I call the value of input1 in java and then perform a calculation on it?
For example...
suppose input1 = x
x + 5 or x*2
and for that matter, how do I have the resulting value appear as constantly updated text output in a specified place on the UI?
In the Activity where you are using this layout XML, you would do this:
private EditText input;
private EditText result;
public void onCreate(Bundle b) {
setContentView(R.layout.my_activity);
// Extract the text fields from the XML layout
input = (EditText) findById(R.id.input1);
result = (EditText) findById(R.id.result);
// Perform calculation when input text changes
input.addKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keycode, KeyEvent keyevent) {
if (keyevent.getAction() == KeyEvent.ACTION_UP) {
doCalculation();
}
return false;
}
});
}
private void doCalculation() {
// Get entered input value
String strValue = input.getText().toString;
// Perform a hard-coded calculation
int result = Integer.parseInt(strValue) * 2;
// Update the UI with the result
result.setText("Result: "+ result);
}
Note that the above includes no error handling: it assumes that you have restricted the input1 text field to allow the input of integer numbers only.
In your XML you can also set android:inputType="number" to only allow numbers as entries.