Changing the values from EditText programmatically - java

I have a decimal number in EditText and I'm trying to change it to always show a decimal part but the user doesn't be able to change the decimal part, only the integer part has to be editable. The decimal part is always a default value.
Example: I have the number 2.025,50 at EditText, if I delete all the digits Ill have 0,50. If I write 10 , Ill have 10,50.
Can anyone help me out ??

I created a function you can use for this, so you just input your number with a decimal and it will give you the decimal part of the number. Use editText changed listener. So when u pass the value being typed by a user call this function and pass the numberWithTheFraction to the function getFractionalPart and add the userinput as shown in the code bellow.
private static double getFractionalPart(double num) {
if (num > 0) {
return num - Math.floor(num);
} else {
return ((num - Math.ceil(num)) * -1);
}
}
you can have a look at this example for an example of editText change listener.
So in the above example when you say textView.setText(getFractionalPart(numberWithTheFraction)+userInput)

Related

Java doesn't print string in the textview

my problem is this:
I have 2 text view, in the first a text that changes from "your X is" to "you are"("you are" is stored in a string) and in the latter a number that could assume any value or, if another value is "0", just become "perfect"(this took from a string).
All this after a click on a button.
The problem is that the first text changes while the second change from 0 but if the first value ( that i said before ) is 0 ( or minus 0 ) just doesn't change... It not assume the value of the string i want.
I hope you got the problem, this is the code.
if (risultato <= 0) {
risultatoX.setText("0");
X.setText(R.string.youAre);
risultatoOre.setText(R.string.perfect);
risultatoOre.setTextColor(Color.parseColor("#259b24"));
hr.setVisibility(View.GONE);
} else {
X.setText(R.string.First);
risultatoOre.setTextColor(Color.parseColor("#757575"));
hr.setVisibility(View.VISIBLE);
}
If you want to get String from resources you need use getResources().getString() method.
For example:
X.setText(getResources().getString(R.string.youAre));
risultatoOre.setText(getResources().getString(perfect));

Strange behaviour managing double and float values (Java)

I have a GUI which works like the following: there are 2 buttons and 1 textField. The textField is used to hold double/float values, 1 of the buttons adds a value (in this case, 0.1) and the other one subtracts (adds -0.1).
Here is my following problem: after pressing one of the buttons many times, the resulting value is not behaving the way I would like. In other words, instead of "1.5" turning into "1.6", it will be something like "1.5999998". I have tried many changes (like changing the variables types and the value to add/subtract), but none of these worked. Here's a piece of my code:
public void sumTextField(){
try{
if(textField.getText() == "")
textField.setText("0.1");
else{
float aux = Float.parseFloat(textField.getText());
aux += 0.10000000;
textField.setText(String.valueOf(aux));
}
}
catch(NumberFormatException nfe){
nfe.printStackTrace();
JOptionPane.showMessageDialog(null, "Please, provide a valid value in the text field!", "Impossible sum", JOptionPane.INFORMATION_MESSAGE);
}
}
public void subtractTextField(){
try{
if(textField.getText() == "")
textField.setText("-0.1");
else{
float aux = Float.parseFloat(textField.getText());
aux -= 0.10000000;
textField.setText(String.valueOf(aux));
}
}
catch(NumberFormatException nfe){
nfe.printStackTrace();
JOptionPane.showMessageDialog(null, "Please, provide a valid value in the text field!", "Impossible subtraction", JOptionPane.INFORMATION_MESSAGE);
}
}
Any ideas are welcome
Your problem is due to the way in which double and float work.
In floating-point arithmetic, the computer only calculates to a certain precision, i.e. after so many decimal places, it just rounds the number off. 0.1 may seem like a nice round number in decimal, but in binary it is recurring - 0.0001100110011 and so on. With each calculation, the rounding-off makes the result a bit more inaccurate. Have a look at this page for a more thorough explanation.
double is more precise than float, but it will still display rounding errors like this.
To circumvent the problem, you could do one of two things. First, as Jon Skeet said in the comments, you could use arbitrary-precision arithmetic like BigDecimal.
Alternatively, you could print out only a couple of decimal places like this:
String answer = String.format("%.2f", myNumber);
This will round off the printed value to 2 decimal places.
Hope this helps!

jformattedtextfield rounded numbers

i have a JFormattedTextField , and i want that when i try to enter a number, example 1002 , that i will rounded to the nearest multiple of 5
1002->1000
304->305
6->5
9->10
1->0
etc..
i've already setup a number format to cancel the grouping, and accepting only numbers
NumberFormat format=NumberFormat.getInstance();
format.setGroupingUsed(false);
pun1[i]=new JFormattedTextField(format); //pun1 and pun2 are the arrays of FIELDS
pun2[i]=new JFormattedTextField(format);
how can i resolve this problem?
I want this editing inside the field, while i'm writing the number, just as when the grouping character appears!
This works for int arguments:
public int roundToClosestFive(int num) {
return (int) (Math.round(num / 5.0) * 5);
}
Remember, to get the int value of the string you've entered you can do: Integer.valueOf(string); and pass that as an argument to the method. To have the text inside the JFormattedTextField change on focus change or enter, you could call the above method from the propertyChange() method of a PropertyChange listener that you can add to the JTextFormattedTextField. Something like this in the propertyChange() method:
public void propertyChange(PropertyChangeEvent e) {
Object source = e.getSource();
if (source == pun1[i]) {
((JFormattedTextField) source).setText(""
+ roundToClosestFive(((Number)pun1[i].getValue()).intValue()));
}
}

Converting double numerical value to text

In the following if statement from a loop in my code, if the given oldsalary[i] doesn't meet these guidelines, I want to restore the previous numerical value of oldsalary[i] to "Error". However I want it to stay as oldsalary[i] since I will be displaying all the oldsalary[i] later in my code.
So basically when all the oldsalary[i] are displayed in another loop, I want to be able to see "Error" so it's know that something was wrong with that value.
I know the way I have it is completely wrong, I just put it like this to make sense. Sorry if it doesn't make any sense.
if(oldsalary[i] < 25000 || oldsalary[i] > 1000000){
JOptionPane.showMessageDialog(null, userinput[i]+"'s salary is not within
necessary limit.\n Must be between $25,000 and $1,000,000. \n If salary is
correct, empolyee is not eligible for a salary increase.");
double oldsalary[i] = "Error";
}
You can't store both the numerical value and an error indicator in a single double value.
Your best bet is to wrap the salary as an object that contains both the salary value and a boolean that indicates the error condition:
class Salary {
private double value;
private boolean error = false;
... constructor, getters and setters
}
And update your code to use the object instead. I.e.
if(oldsalary[i].getValue() < 25000 || oldsalary[i].getValue() > 1000000) {
oldsalary[i].setError(true);
...
}
So later you can do
if (oldsalary[i].isError()) {
// display error message
}
You can use an extra List that stores the indices that are no pass your requirement test.
List<Integer> invalidIndices = new ArrayList<>();
for (...){
if(oldsalary[i] < 25000 || oldsalary[i] > 1000000){
JOptionPane.showMessageDialog(null, userinput[i]+"'s salary is not within
necessary limit.\n Must be between $25,000 and $1,000,000. \n If salary is
correct, empolyee is not eligible for a salary increase.");
invalidIndices.add(i);
}
}

solve through a loop in java

I have a text box(having name b) and one submit button in index.jsp. I will enter something in text box then after clicking submit i get that value by in server side find.jsp. In find.jsp i get the value by request.getParameter("b"); In find.jsp calaculation is done as shown below:
double c=0;
double d=0;
7800.0/12 and 2640.0/12 are fixed.
if request.getParameter("b")=1 then
c=7800.0/12*5;// 5 is multiplied with above number(in first one)
d=2640.0/12*5;// 5 is multiplied with above number(in second one)
if request.getParameter("b")=2 then
c=7800.0/12*8;// here 5 gets incremented by 3 and became 8(in first one)
d=2640.0/12*8;// same also here( in second one)
Similarly if i will enter 20 then accordingly c and d will be calculated.
I cannot use if-else as any value can be entered in client side and accordingly c and d will be calculated in server side.
How can i implement it in a loop? Many thanks
try
double devide=2.0
devide = Integer.parseInt(request.getParameter("b"))*3+devide
c=7800.0/(12*devide);
d=2640.0/(12*devide);
You can use for any value to count below one logic.
int value = Integer.parseInt(request.getParameter("b"));
double x=2.0;
double valueForDevide = (value*3)+x;
c=7800.0/(12*valueForDevide );
d=2640.0/(12*valueForDevide );

Categories