Java - Convert int number - java

What I want to do :
I made a BMI calculator (Formula=(KG*KG)/M)
The input takes eg 186 but i get an error when inserting 1.86 (For height in metres)
java.lang.NumberFormatException: For input string: "1.86"
Here is my code :
if (txtHeight.getText().length() > 0 && txtWeight.getText().length() > 0){
height = Integer.parseInt(txtHeight.getText());
heightsqr = (int) Math.pow(height, 2);
mass = Integer.parseInt(txtWeight.getText());
bmi = (heightsqr/ mass);
lblBmi.setText("Current BMI : " + Integer.toString(bmi));
}
else{
JOptionPane.showMessageDialog(this, "Please enter your weight in KG and your Height in M");
}
It's a pretty basic error that I just cant seem to fix

As the stacktrace says, you can't convert 1.86 to int. Why? because it's a double.
try:
mass = Double.parseDouble(txtWeight.getText());
In Java, we have types. int can only store integer. Real numbers can be stored in floats and doubles but remember, that you can lose precision.
I don't know your whole code, so I can't tell you, what is the type of mass. In case you have the following somewhere in your code:
int mass;
change it to:
double mass;
Some random thoughts:
As you have already seen, there is a possibility that the Exception will be thrown. It happens depending on user input I believe. In Java we have a mechanism to secure. It's a try-catch block. It can be used for example in the following way:
try {
mass = Double.parseDouble("1,86");
} catch (NumberFormatException e) {
//somehow notify user that he has mistaken and work it out according to your business logic.
}
I strongly recommend reading this tutorial which I have provided on StackOverflow question What is a NumberFormatException and how can I fix it.

an Integer is a non-decimal value, hence 1.86 is invalid.
Try converting it into a Double:
Double.parseDouble(txtHeight.getText());

you try to convert a double into an int. thats causing the error. if you want to fix it, you should either only accept integers or only doubles. otherwise you will need 2 if-statements. converting to double looks like this: height = Double.parseDouble(txtHeight.getText());

Related

How to solve java.lang.NumberFormatException: For input string: "396.00"

I have made a small application in java. I want to insert supplier payment in mysql database.Now the issue is when i try to subtract total balance with total payment and enter in balance column. so it give me error like java.lang.NumberFormatException: For input string: "396.00".
So how can I solve it
if(jCheckBox1.isSelected())
{
String bx="Insert into supplierpaymenttable(Supplier_ID,SupplierInvoice_ID,User_ID,InvoiceNo,TotalAmount,PaymentAmount,RemainingBalance) VALUES (?,?,?,?,?,?,?)";
PreparedStatement pay=conn.prepareStatement(bx);
int k=Integer.parseInt(jTextField5.getText());
int cx=k-k;
pay.setString(1,String.valueOf(supplier));
pay.setString(2,String.valueOf(det));
pay.setString(3,"1");
pay.setString(4, String.valueOf(invoie));
pay.setInt(5, Integer.valueOf(jTextField5.getText()));
pay.setInt(6, Integer.valueOf(jTextField5.getText()));
pay.setInt(7,Integer.valueOf(cx));
int rsdets= pay.executeUpdate();
}
396.00 is a Double not an int value.
So you have to parse it as a double:
Double.valueOf(cx).intValue()
So your code looks like:
if(jCheckBox1.isSelected())
{
String bx="Insert into supplierpaymenttable(Supplier_ID,SupplierInvoice_ID,User_ID,InvoiceNo,TotalAmount,PaymentAmount,RemainingBalance) VALUES (?,?,?,?,?,?,?)";
PreparedStatement pay=conn.prepareStatement(bx);
int k=Double.valueOf(jTextField5.getText()).intValue();
int cx=k-k;
pay.setString(1,String.valueOf(supplier));
pay.setString(2,String.valueOf(det));
pay.setString(3,"1");
pay.setString(4, String.valueOf(invoie));
pay.setInt(5, Integer.valueOf(jTextField5.getText()));
pay.setInt(6, Integer.valueOf(jTextField5.getText()));
pay.setInt(7,Double.valueOf(cx).intValue());
int rsdets= pay.executeUpdate();
}
As Jens mentioned. You're attempting to cast a double/float value to int. So depending on what you're trying to do.
If you're accepting decimal points, then it's better to change your DB schema to accept decimal and use Double.valueOf(cx).
If you're accepting Integer only, then you have to parse the input and either truncate or round off the decimal points. (int) Math.round(Double.valueOf(cx))
Some people multiply the amount by 100 to include cents as a way to bypass dealing with doubles
Edit:
Can you post the stacktrace? Looking more closely at the code, cx is already an integer and you're doing Integer.valueOf(cx) which does nothing. Also isn't cx always 0 since you're doing k-k? Are you sure the IDs are string values? That part looks weird to me.

How to prevent Java from auto rounding up

I have a method which returns a double
public double getOdds() {
return odds;
}
This works completly fine. However, the problem is when the data is displayed, it automatically rounds the inserted value up. I want to prevant that, and get a value with 2 decimals.
Here are my JSP where I call the method. The ArrayList "bets" consist of all values entered by the user. But, as explained above, when the user enters 2.75 then it will return 3.0
ArrayList <bets> bets = betsDAO.getBets(x, y);
for (bets bet : bets) {
<td><%=bet.getOdds()%></td>
}
I'm still new to Java, and have tried looking for solutions, but unfortunatly I have not been able to solve the issue.
when the user enters 2.75 then it will return 3.0
The only reason for that to happen is if the value is limited to zero decimals at some point. Java only does that for int (or long or short or char or byte) values, and those are truncated, so result would be 2, not 3.0.
The only round-to-nearest I can envision is caused by the database or the JDBC driver:
The column type in the database is INTEGER or NUMBER(5,0) or something like that. Check your database schema.
The code reading the database (betsDAO) is calling getInt(...) and the JDBC driver rounds the value for you.
Anyway, the error is in code you haven't shown.
it depends on which data type you intend on working with, but this
should do the trick for you
public class Rounding {
public static void main(String[] args) {
//using string format
double input = 3.14159265359;
System.out.println("double : " + input);
System.out.println("double : " + String.format("%.2f", input));
//using Decimal format
double num = 1.34567;
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println(df.format(num));
}
}
OUTPUT:
double : 3.14159265359
double : 3.14
double : 3.14
OUTPUT:
1.346
so you can be more specific here with the decimal point to return. it all depends on the importance of the decimal precision for your project
Couldn't Math.floor help with the rounding? it rounds down, and if you ever need to use rounding up then use Math.ceil.
hopefully this helps!

Converting String/Double to Int in Android

Hello new to android/Java,
I am using JSON to Parse values as strings and doubles. I am getting strings/doubles such as "6503.04" or "12.3942" etc. I am looking to see if I can convert these strings into an integer and also doubles into integers. I just need to get rid of the decimals points in the easiest way possible. How can I make that happen?
Any help appreciated.
double x = Double.parseDouble(your_string);
int y = (int) x;
y is going to have value of x with decimals cutted of.
Before casting to int you are able to floor or ceil the number if you want.
Don't forget that parsing functions usually throw an exception when your_string is not a number.
//get the value from json as double then get the integer
Double number = jsonObject.getDouble('longitude')
int newNumber = number.intValue()

String to Integer Converting gives wrong output

In my program i'm posting the payment amount value to controller and i'm converting that value to Integer. Because I need to convert this value to cents before calling web service.
I'm using java and convert String to Integer code given below
(int)(Double.parseDouble(httpRequest.getParameter(PAYMENT_AMOUNT).trim()) * 100);
payment.jsp
page look like this
Payment Amount: <input type="text" id="paymentAmount" name="paymentAmount" value="1.00" />
For many input values it gives the correct output.
But for some values like 8.03 as input it return 802 as output value . This happens in 9.03,9.04 ,10.03,10.04,11.03 etc ... what could be the reason for this issue?
You need to round the result. The problem you have is that floating point numbers are almost but not exactly the number it appears when printed as a string. This shows up as a problem when you perform calculations.
I suggest you try
(int) Math.round( Double.parseDouble( httpRequest.getParameter(PAYMENT_AMOUNT).trim()) * 100);
In your specific case, you can see with BigDecimal what the actual representation of a double is
double d = 8.03;
BigDecimal bd = new BigDecimal(d);
System.out.println("bd: " + bd);
double d100 = d * 100;
System.out.println("d100: " + d100);
int i100 = (int) d100;
System.out.println("i100: " + i100);
int r100 = (int) Math.round(d100);
System.out.println("r100: " + r100);
prints
bd: 8.0299999999999993605115378159098327159881591796875
d100: 802.9999999999999
i100: 802
r100: 803
So you can see the actual value of 8.03 is slightly less than 8.03 which means however that when you * 100 and round down it means that you get 802 not 803 as expected.
The best solution is to round the result which finds the closest representable value.
As a side note, you might want to reconsider using int types to store cent values esp when dealing with large numbers.
To add more to earlier answers on floating-point issues in Java, and the need for BigDecimal, refer to some explanation here:
http://www.drdobbs.com/jvm/javas-floating-point-imprecision/240168744
You can change your code to:
(new BigDecimal(httpRequest.getParameter(PAYMENT_AMOUNT).trim(), MathContext.DECIMAL64)).multiply(new BigDecimal(100, MathContext.DECIMAL64)).intValue()
Another note: I would be cautious about assuming that you will get a String object back in the getParameter() call above esp. if someone is attempting to call your service without passing the PAYMENT_AMOUNT parameter.

Exponential values vs double ( big decimal conversion already used)

i am using following function to format the double value to x.xx , but after that the result value started to end up with exponential value ( i have already read the answers which are advising to use the DecimalFormat or to plain text () methods but every where the system is giving error to change the types ...return types i am lost a bit now
can some one please help me in following method tweaks so that the returning values can be displayed as normal number instead of 3.343E32
Please note that the following function FD is used many times in code so i want to change it here only so i dont have to apply the formatting each and every results / variable..
public double fd(double x) {
BigDecimal bd_tax = new BigDecimal(x);
BigDecimal formated = bd_tax.setScale(2, BigDecimal.ROUND_UP);
x = Double.valueOf(formated.doubleValue());
return x;
}
You say, "...to format the double value...", but there is no code in your example that formats anything. Your fd(x) function takes a double as its argument, and it returns a double. It doesn't do anything else.
If your numbers really are in the neighborhood of 3.343E32, Then they're going to have a lot of digits: 33 digits before the decimal point. Is that what you were expecting?
Suggest you look at String.format() if you are trying to turn the double value into human readable text. Something like this, perhaps:
public String fd(double x) {
return String.format("%.2f", x);
}

Categories

Resources