calculating numbers after . (dot) in java - java

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!

Related

Getting number in floating format from database in my App

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.

Parsing string to double/float throwing errors

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);

OutOfBounds Exception ; working with Fractions

I'm writing a program called FractionScaler that takes in a fraction from the user using Scanner, and then manipulates it. I've written a fraction class that handles all the calculations. The user is supposed to enter a fraction like this: "2/3" or "43/65" etc... This part works fine, the problem is when there is space between the integers: " 3 / 4 " or "2/ 5" etc... An "OutOfBoundsException: String index out of range: -1" occurs. Let me explain further.
//This is the user inputted fraction. i.e. "2/3" or " 3 / 4"
String frac = scan.next();
//This finds the slash separating the numerator from the denominator
int slashLocate = frac.indexOf("/");
//These are new strings that separate the user inputted string into two parts on
//either side of the "/" sign
String sNum = frac.substring(0,slashLocate); //This is from the beginning of string to the slash (exclusive)
String sDenom = frac.substring(slashLocate+1,frac.length()); //from 1 after slash to end of string
//This trims the white space off of either side of the integers
sNum = sNum.trim(); //Numerator
sDenom = sDenom.trim(); //Denominator
What I thought should be left is just two strings that look like integers, now I need to turn those strings into actual integers.
//converts string "integer" into real int
int num = Integer.parseInt(sNum);
int denom = Integer.parseInt(sDenom);
Now that I have two integers for the numerator and the denominator, I can plug them into a constructor for the fraction class I wrote.
Fraction fraction1 = new Fraction(num, denom);
I doubt this is the best way to go about this, but it is the only way I could think of. When the user inputted fraction has no spaces, EX. "2/3" or "5/6" , the program works fine.
When the user input has spaces of any kind, EX. "3 / 4" or " 3 /4" , the following error is shown:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1.
The terminal points to line 17 of my code which is this line above:
String sNum = frac.substring(0,slashLocate);
I don't know why I'm getting an out of bounds error. Can anyone else figure it out?
If something is unclear or I didn't give enough info, just say so.
Thanks very much.
Try String frac = scan.nextLine();
I think next() won't get anything after a space.
From the documentation:
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.
That means this won't work, because when entering 2 / 3, frac will just contain the text "2":
String frac = scan.next();
//This finds the slash separating the numerator from the denominator
int slashLocate = frac.indexOf("/");

decimalFormat to save as a double

I'm doing a project where I need to save some user input as a double, formatted to 4 decimal places. I can manage to get the string to have the right format, but parsing it to a Double breaks it. Here is an example of what i'm doing..
DecimalFormat format = new DecimalFormat("#.0000");
String example = "1.23";
Double num = Double.parseDouble(example);
String str = format.format(num);
Double num1 = Double.parseDouble(str);
System.out.println(num1);
this prints
1.23
when i'd like it to print
1.2300
You're confusing the number with the String representation of the number. These are two very different things. A floating point number has an accuracy, but it doesn't understand what display significant digits mean. It's like asking the abstract number 0 to know that 00 is.
To display the number correctly, use the formatter that you have already created:
System.out.println(format.format(num1));

Java Convert from Scientific Notation to Float

I have a program that I am working on which would effectively convert binary, decimal, or hex numbers to other formats (don't ask why I'm doing this, I honestly don't know). So far I only have a binary - decimal conversion going, and it works fine however whenever the binary number entered is 8 digits or more it crashes.
As far as I can tell when I input the number 10011001 it gets translated to scientific notation and becomes 1.0011001E7 which wouldn't really be a problem, except that the way I am converting the numbers involves creating a string with the same value as the number and breaking it into individual characters. Unfortunately, this means I have a string valued "1.0011001E7" instead of "10011001", so when I cut up the characters I hit the "." and the program doesn't know what to do when I try to make calculations with that. So basically my question comes down to this, how do I force it to use the not-scientific notation version for these calculations?
Thanks for all your help, and here is the code if it helps at all:
//This Splits A Single String Of Digits Into An Array Of Individual Digits
public float[] splitDigits(float fltInput){
//This Declares The Variables
String strInput = "" + fltInput;
float[] digit = new float[strInput.length() - 2];
int m = 0;
//This Declares The Array To Hold The Answer
for (m = 0; m < (strInput.length() - 2); m++){
digit[m] = Float.parseFloat(strInput.substring(m, m + 1)); //Breaks here
}
//This Returns The Answer
return digit;
}
Just use BigDecimal
BigDecimal num = new BigDecimal(fltInput);
String numWithNoExponents = num.toPlainString();
Note here the fltInput will be automatically converted to a double.

Categories