I use EditText for a form in my app , and asking user to enter a number then after getting the number (double) from EditText storing it on the database , everything works fine till here, but when i want to show the number in my app it shows in floating format e.g if user enter 32453905 in my app i get 32453905.0 which i really don't need how to fix it.
code to convert text to double
private double textToDouble(String number)
{
if (number != null && number.length() > 0)
return Double.parseDouble(number);
else
return 0;
}
code for getting number from database
String stringNumber = Double.toString(user.getNumber());
editTextNationalNumber.setText(stringNumber);
Since you allow users to enter double value numbers you need to check if the number has any digits after the decimal point so:
double d = user.getNumber();
String text = "";
if (d % 1 == 0) {
text = Integer.toString((int)d);
} else {
text = Double.toString(d);
}
editTextNationalNumber.setText(text);
#zolfa have to tried user.getNumber().toString() or String.valueOf(user.getNumber());
You can do following:
//number without decimals
int number = (int) user.getNumber();
String stringNumber = Integer.toString(number);
If user can also enter decimal values, than you can handle both like this:
//number without decimals
double doubleNumber = user.getNumber();
int intNumber = (int) doubleNumber;
String stringNumber;
if(intNumber == doubleNumber)
stringNumber = Integer.toString(intNumber);
else
stringNumber = Double.toString(doubleNumber);
This will ensure that you will display correct decimal value if user enters one.
If the numbers dont have to be put in as text you can use the Scanner function of java
Import java.util.Scanner;
And to get input use
double number = in.nextDouble();
The value will get stored in number as a double
A double will always return a decimal number. So try to use type casting like
(int) variabeleAsDouble
Then your program will accept decimals, but rounds it to a whole number.
Related
I am new to Java. creating calculator which calculates number from user input.
I have 2 Jtextfield in my application where user input numbers.
For example in first field user input 45678.230 and in second field 23214.210 which gives me subtraction result is 22464 but everything i want is full result followed by .(dot) so my answer should be 22464.02
String n1opn = n1open.getText();
String n1clsd = n1close.getText();
double n1intopen = (int) Double.parseDouble(n1opn);
double n1intclose = (int) Double.parseDouble(n1clsd);
double n1ltr = n1intclose - n1intopen;
System.out.println("output "+ n1ltr);
You seem to be casting your inputs to an int. Integers don't have any decimal bits so using double is correct for your case!
I have a problem with my code's formatting. At the end, it's supposed to print out its results. I am using a printf statement, but it returns numbers that aren't as precise as I need them to be. For example, if one number should be 76.83200000000001, it returns as 76.83200. It is also adding unnecessary zeros at the end of numbers, and if a number should be 28.0, it turns into 28.000000. If possible, can we do this without a BigDecimal variable? Here's my code so far (NOTE: there are spaces in front of some strings, that's because the website I'm submitting to requires that for some reason):
import java.util.Scanner;
public class Population {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
double startingNumber, dailyIncrease, daysWillMultiply, temp, population;
System.out.print("Enter the starting number organisms: ");
startingNumber = stdin.nextDouble();
while(startingNumber < 2) {
System.out.print("Invalid. Must be at least 2. Re-enter: ");
startingNumber = stdin.nextDouble();
}
System.out.print("Enter the daily increase: ");
dailyIncrease = stdin.nextDouble();
while(dailyIncrease < 0) {
System.out.print("Invalid. Enter a non-negative number: ");
dailyIncrease = stdin.nextDouble();
}
System.out.print("Enter the number of days the organisms will multiply: ");
daysWillMultiply = stdin.nextDouble();
while(daysWillMultiply < 1) {
System.out.print("Invalid. Enter 1 or more: ");
daysWillMultiply = stdin.nextDouble();
}
temp = startingNumber * dailyIncrease;
population = startingNumber;
System.out.println("Day\t\tOrganisms");
System.out.println("-----------------------------");
System.out.println("1\t\t" + startingNumber);
for (int x = 2; x <= daysWillMultiply; x++) {
population += temp;
temp = population * dailyIncrease;
System.out.printf(x + "\t\t%f\n", population);
}
}
}
Well, I deleted my previous answer as it was absolutely wrong (thanks to #JohnKugelman for pointing this out). I thought that precision is lost due to converting to float, but it is not true.
According to the formatter documentation, here's what happens when %f flag is used:
The magnitude m (absolute value of the argument) is formatted as
the integer part of m, with no leading zeroes, followed by the
decimal separator followed by one or more decimal digits representing
the fractional part of m.
The number of digits in the result for the fractional part of m is equal to the precision. If the precision is not specified then
the default value is 6
If the precision is less than the number of digits which would appear
after the decimal point in the string returned by
Float.toString(float) or Double.toString(double) respectively,
then the value will be rounded using the round half up algorithm.
Otherwise, zeros may be appended to reach the precision.
That's why you get unnecessary zeros and cut digits.
The documentation suggests to use Float.toString(float) or Double.toString(double) for a canonical representation of the value.
If you want to use System.out.printf(...);, you can just replace your %f flag with %s - in this case the argument will be converted to a string (the result is obtained by invoking the argument's toString() method, and this is what you need). For example, you could rewrite this line:
System.out.printf(x + "\t\t%f\n", population);
as follows:
System.out.printf("%d\t\t%s\n", x, population);
This will print the exact value of your population.
Check first answer of this thread, it maybe helpful.
How many significant digits have floats and doubles in java?
It's important to understand that the precision isn't uniform and that
this isn't an exact storage of the numbers as is done for integers.
I'm learning JAVA and recently I had the same problem with a few training tasks.
I have a some numbers and some of them are starting with 0. I found out that these numbers are octal which means it won't be the number I wanted or it gives me an error (because of the "8" or the "9" because they are not octal digits) after I read it as an int or long...
Until now I only had to work with two digit numbers like 14 or 05.
I treated them as Strings and converted them into numbers with a function that checks all of the String numbers and convert them to numbers like this
String numStr = "02";
if(numStr.startsWith("0")) {
int num = getNumericValue(numStr.charAt(1));
} else {
int num = Integer.parseInt(numStr);
}
Now I have an unkown lot of number with an unknown number of digits (so maybe more than 2). I know that if I want I can use a loop and .substring(), but there must be an easier way.
Is there any way to simply ignore the zeros somehow?
Edit:
Until now I always edited the numbers I had to work with to be Strings because I couldn't find an easier way to solve the problem. When I had 0010 27 09 I had to declare it like:
String[] numbers = {"0010", "27", "09"};
Because if I declare it like this:
int[] numbers = {0010, 27, 09};
numbers[0] will be 8 instead of 10 and numbers[2] will give me an error
Actually I don't want to work with Strings. What I actually want is to read numbers starting with zero as numbers (eg.: int or long) but I want them to be decimal. The problem is that I have a lot of number from a source. I copied them into the code and edited it to be a declaration of an array. But I don't want to edit them to be Strings just to delete the zeros and make them numbers again.
I'm not quite sure what you want to achieve. Do you want to be able to read an Integer, given as String in a 8-based format (Case 1)? Or do you want to read such a String and interpret it as 10-based though it is 8-based (Case 2)?
Or do you simply want to know how to create such an Integer without manually converting it (Case 3)?
Case 1:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 8-based integer.
Integer number = Integer.parseInt(input, 8);
Case 2:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 10-based integer (default).
Integer number = Integer.parseInt(input);
Case 3:
// Java interprets this as octal number
int octal = 0235;
// Java interprets this as hexadecimal number
int hexa = 0x235
// Java interprets this as decimal number
int decimal = 235
You can expand Case 1 to a intelligent method by reacting to the indicator:
public Integer convert(final String input) {
String hexaIndicator = input.substring(0, 2);
if (hexaIndicator.equals("0x")) {
return Integer.parseInt(input.substring(2), 16);
} else {
String octaIndicator = input.substring(0, 1);
if (octaIndicator.equals("0")) {
return Integer.parseInt(input.substring(1), 8);
} else {
return Integer.parseInt(input);
}
}
}
I am extracting couple of values like 1234, 2456.00 etc from UI as string. When I try to parse this string to float, 1234 is becoming 1234.0 and when I tried to parse as double its throwing error. How can I solve this?
I am using selenium web driver and java. Below are few things I tried.
double Val=Double.parseDouble("SOQ");
double Val=(long)Double.parseDouble("SOQ");``
I think you mixed it up a bit when trying to figure out how to parse the numbers. So here is an overview:
// lets say you have two Strings, one with a simple int number and one floating point number
String anIntegerString = "1234";
String aDoubleString = "1234.123";
// you can parse the String with the integer value as double
double integerStringAsDoubleValue = Double.parseDouble(anIntegerString);
System.out.println("integer String as double value = " + integerStringAsDoubleValue);
// or you can parse the integer String as an int (of course)
int integerStringAsIntValue = Integer.parseInt(anIntegerString);
System.out.println("integer String as int value = " + integerStringAsIntValue);
// if you have a String with some sort of floating point number, you can parse it as double
double doubleStringAsDoubleValue = Double.parseDouble(aDoubleString);
System.out.println("double String as double value = " + doubleStringAsDoubleValue);
// but you will not be able to parse an int as double
int doubleStringAsIntegerValue = Integer.parseInt(aDoubleString); // this throws a NumberFormatException because you are trying to force a double into an int - and java won't assume how to handle the digits after the .
System.out.println("double String as int value = " + doubleStringAsIntegerValue);
This code would print out:
integer String as double value = 1234.0
integer String as int value = 1234
double String as double value = 1234.123
Exception in thread "main" java.lang.NumberFormatException: For input string: "1234.123"
Java will stop "parsing" the number right when it hits the . because an integer can never have a . and the same goes for any other non-numeric vales like "ABC", "123$", "one" ... A human may be able to read "123$" as a number, but Java won't make any assumptions on how to interpret the "$".
Furthermore: for float or double you can either provide a normal integer number or anything with a . somewhere, but no other character besides . is allowed (not even , or ; and not even a WHITESPACE)
EDIT:
If you have a number with "zeros" at the end, it may look nice and understandable for a human, but a computer doesn't need them, since the number is still mathematically correct when omitting the zeros.
e.g. "123.00" is the same as 123 or 123.000000
It is only a question of formatting the output when printing or displaying the number again (in which case the number will be casted back into a string). You can do it like this:
String numericString = "2456.00 "; // your double as a string
double doubleValue = Double.parseDouble(numericString); // parse the number as a real double
// Do stuff with the double value
String printDouble = new DecimalFormat("#.00").format(doubleValue); // force the double to have at least 2 digits after the .
System.out.println(printDouble); // will print "2456.00"
You can find an overview on DecimalFormat here.
For example the # means "this is a digit, but leading zeros are omitted" and 0 means "this is a digit and will not be omitted, even if zero"
hope this helps
Your first problem is that "SOQ" is not a number.
Second, if you want create a number using a String, you can use parseDouble and give in a value that does not have a decimal point. Like so:
Double.parseDouble("1");
If you have a value saved as a long you do not have to do any conversions to save it as a double. This will compile and print 10.0:
long l = 10l;
double d = l;
System.out.println(d);
Finally, please read this Asking a good question
The problem is you cannot parse non-numeric input as a Double.
For example:
Double.parseDouble("my text");
Double.parseDouble("alphanumeric1234");
Double.parseDouble("SOQ");
will cause errors.
but the following is valid:
Double.parseDouble("34");
Double.parseDouble("1234.00");
The number you want to parse into Double contains "," and space so you need first to get rid of them before you do the parsing
String str = "1234, 2456.00".replace(",", "").replace(" ", "");
double Val=Double.parseDouble(str);
Hey I am trying to convert string text boxes so i can multiply two variables and the display it in a third text box. My text boxes are txtTotalPre and i am trying to multiply this number by 1 and then display it in txtTotal.
String number = txtSub.getText();
String.valueOf(number);
int price = 1;
txtTotal.setText(number * price);
try
int number = Integer.parseInt(txtSub.getText());
instead of
String number = txtSub.getText();
String.valueOf(number);