can anybody look at this code and tell me why the exception happens?
public static void main(String[] args)
{
int total =100;
int discount_Ammount = 20 ;
int newAccount=Integer.parseInt( String.valueOf(Math.floor(total - discount_Ammount)).trim());
}
Method floor returns double value , then I make casting to integer, so I cast it to string then to integer... please, can anybody help?
You aren't "casting" anything. trim() removes whitespace only, which will never be present in the result of String.valueOf(double).
Use a cast:
int newAccount = (int) Math.floor(total - discount_Ammount);
Java is a strongly typed programming language, not a scripting language. Implicit conversions between strings and other types are not supported.
Or, get rid of the floor() operation altogether, since you are working with an int quantity already, and floor() is meaningless:
int newAccount = total - discount_Ammount;
If you are working with money, use the BigDecimal class so that you can use the round-off rules required by your accounting system. You won't have control of that when using double.
Did you try this?
int newAccount = (int) Math.floor(total - discount_Ammount);
Or even this!
int newAccount = total - discount_Ammount;
No need to do Integer.parseInt( String.valueOf(
To cast to int, just do (int)(blah)
So int newAccount=(int)(Math.floor(total - discount_Ammount));
Related
The Java code is as follows:
String s = "0.01";
int i = Integer.parseInt(s);
However this is throwing a NumberFormatException... What could be going wrong?
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;
The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense.
A double or a float datatype can hold rational numbers.
The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.
int i = (int) 0.9999;
i will be zero.
0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.
Use,
String s="0.01";
int i= new Double(s).intValue();
String s="0.01";
int i = Double.valueOf(s).intValue();
This kind of conversion is actually suprisingly unintuitive in Java
Take for example a following string : "100.00"
C : a simple standard library function at least since 1971 (Where did the name `atoi` come from?)
int i = atoi(decimalstring);
Java : mandatory passage by Double (or Float) parse, followed by a cast
int i = (int)Double.parseDouble(decimalstring);
Java sure has some oddities up it's sleeve
Using BigDecimal to get rounding:
String s1="0.01";
int i1 = new BigDecimal(s1).setScale(0, RoundingMode.HALF_UP).intValueExact();
String s2="0.5";
int i2 = new BigDecimal(s2).setScale(0, RoundingMode.HALF_UP).intValueExact();
suppose we take a integer in string.
String s="100";
int i=Integer.parseInt(s);
or
int i=Integer.valueOf(s);
but in your question the number you are trying to do the change is the whole number
String s="10.00";
double d=Double.parseDouble(s);
int i=(int)d;
This way you get the answer of the value which you are trying to get it.
use this one
int number = (int) Double.parseDouble(s);
Use Double.parseDouble(String a) what you are looking for is not an integer as it is not a whole number.
One more solution is possible.
int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))
Example:
Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))
Output
10
Hello, here's my issue : I keep having an error telling me that the types are incompatible even though my "R.id.total_akylux" is a Number(Decimal) in the XML file, and the result is given in decimal. I don't really understand why do i keep having this error. If someone could help me, it'd be really useful. Thank you
First of all: Mind QBrutes comment and re-think your concept.
You are trying to assign a double to an int, this is exactly what the error tells you. Now that int you are using isn't even your number but the ID of your resource. If you really want to store an int in your resources, follow this answer: https://stackoverflow.com/a/19297523/2694254
Regarding your error
Double can't be assigned to int without some manual casting.
If you are confused by the int/double casting stuff:
int numberInt = 1;
double numberDouble = 1.8;
//what you are trying to do:
numberInt = numberDouble;
//what you could do:
numberInt = (int) numberDouble; //numberInt is now 1
//with rounding:
numberInt = (int) Math.round(numberDouble); //numberInt is now 2
Also, you could store a float in xml instead of int: https://stackoverflow.com/a/20120240/2694254
You could also store the double as String, but that would require even more casting.
First of all, I'd like to thank you to take time to answer me even though i'm new to this language. I understand what you're saying to me so i started changing my code like this
double prix = 15.90;
double m2 = (longueur_akylux*largeur_akylux)/100;
double total = prix*m2* quantite;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.akylux);
}
#SuppressWarnings("unused")
public void calcul_akylux(View v){
TextView t = (TextView) findViewById(R.id.total_akylux);
t.setText(total);
}
So, if i create a Number(Decimal) in the XML , it won't wait for a double ? How can i do so this Number is a decimal ?
Thank you
for (int i = 0; i < 18; i++) {
line = file.readLine();
String[] word = line.split(";");
appartment[i] = new Appartment();
appartment[i].floor= Integer.parseInt(word[0]);
appartment[i].name = word[1];
appartment[i].money= Double.parseDouble(word[2]);
appartment[i].owner= word[3];
}
Could someone tell my why this is not working? Im reading from a file. I am trying to convert money from string to double, but it says
possible loss of precision.
required: int
found: double
I need doubles so the owners account also can go negative.
- It seems that appartment is an Array of type Appartment, where the Appartement's object field named money is in int type.
- But you are assingnig it the value as double type, so you will need an explicit cast from double to int,
Eg:
appartment[i].money= (int) Double.parseDouble(word[2]);
Apparently appartment[i].money= Double.parseDouble(word[2]); is a problem here. If the type of money is int, either you should cast the value of word[2] to int like
appartment[i].money = (int(Double.parseDouble(word[2]));
or you should parse as an integer something like
appartment[i].money= Integer.parseInt(word[2]);
use this,
appartment[i].money = Integer.parseInt(word[2]);
You probably have in defenition of appartment that money is int, try to change it to double...
The best practice when representing money in Java is to use BigDecimal. See: http://www.javapractices.com/topic/TopicAction.do?Id=13 for more details.
How do i go about using compareto for a double and i want to turn it into an int?
An example would be nice. I have been searching the java api.
also is it possible to use if and else statements with a String toString method? Mine has kept on crashing for special cases.
im a total noob to java i guess i been reading constantly to learn
If you want to compare an integer with a double you will need to convert the integer to a double. Please be aware that this won't work the other way round as an int couldn't hold all the values a double can: Values will be round down
double d = 12.3;
return (int)d;
will return 12! and doubles can hold values way bigger and small than int could
double d = 1.337E42
return (int)d;
returns 2147483647! There are many orders of magnitude in between. So please always convert the int to a double to prevent this to happen.
You can use following code for comparison:
int compare(double d, int i) {
return new Double(d).compareTo(new Double(i));
}
But keep in mind that Double differs from double as Double is an object and not a primitive type, so there will be more overhead when handling a Double compared to using a double or int.
As for the second part of your question I don't really understand what's your question/intention. Please try to clarify it.
you can try something like this
Double d = 10.0;
Integer i = 10;
d.compareTo(i.doubleValue());
or
i.compareTo(d.intValue());
I'm not sure which one you need.
You do not want to convert to String because that would compare the numbers lexicographically rather than numerically.
I will take your question to mean, "How do I create a compareTo() method for doubles?"
I also think you are using this to implement a data structure for doubles.
Here is how I would go about it.
When you construct a data structure, you will construct it as a Double object.
Double is a built-in class in java.lang package that boxes the double primitive.
Then, java will automatically cast them to that type.
The reason you want to use the Double class as the defining type for your data structure is so that you can use its built-in compareTo method. There is no way to make the primitive data type double contain the compareTo method.
Here is some code to help you get started for example:
TreeMap <Double, String> myDoubleMap = new TreeMap <Double, String> (10);
for (int i = 0; i < 10; i++)
myDoubleMap.put ( Math.sqrt( 10.0 * i) , "" + i);
System.out.println(myDoubleMap);
(Make sure you import java.util.TreeMap if you are to run this example)
I can only guess at your exact requirements. You should try to refine them a little more clearly.
If you want to compare doubles and ints, it may be tough. You have two options.
one: cast the double to an int, and compare
int compare(double d, int i) {
int dint = (int)d;
return Integer.compare(dint,i);
}
int compare(int i, double d) {
int dint = (int)d;
return Integer.compare(i,dint);
}
two: cast the int to a double, and compare
int compare(double d, int i) {
double idouble = (double)i;
return Double.compare(d,idouble);
}
int compare(int i, double d) {
double idouble = (double)i;
return Double.compare(d,idouble);
}
The Java code is as follows:
String s = "0.01";
int i = Integer.parseInt(s);
However this is throwing a NumberFormatException... What could be going wrong?
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;
The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense.
A double or a float datatype can hold rational numbers.
The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.
int i = (int) 0.9999;
i will be zero.
0.01 is not an integer (whole number), so you of course can't parse it as one. Use Double.parseDouble or Float.parseFloat instead.
Use,
String s="0.01";
int i= new Double(s).intValue();
String s="0.01";
int i = Double.valueOf(s).intValue();
This kind of conversion is actually suprisingly unintuitive in Java
Take for example a following string : "100.00"
C : a simple standard library function at least since 1971 (Where did the name `atoi` come from?)
int i = atoi(decimalstring);
Java : mandatory passage by Double (or Float) parse, followed by a cast
int i = (int)Double.parseDouble(decimalstring);
Java sure has some oddities up it's sleeve
Using BigDecimal to get rounding:
String s1="0.01";
int i1 = new BigDecimal(s1).setScale(0, RoundingMode.HALF_UP).intValueExact();
String s2="0.5";
int i2 = new BigDecimal(s2).setScale(0, RoundingMode.HALF_UP).intValueExact();
suppose we take a integer in string.
String s="100";
int i=Integer.parseInt(s);
or
int i=Integer.valueOf(s);
but in your question the number you are trying to do the change is the whole number
String s="10.00";
double d=Double.parseDouble(s);
int i=(int)d;
This way you get the answer of the value which you are trying to get it.
use this one
int number = (int) Double.parseDouble(s);
Use Double.parseDouble(String a) what you are looking for is not an integer as it is not a whole number.
One more solution is possible.
int number = Integer.parseInt(new DecimalFormat("#").format(decimalNumber))
Example:
Integer.parseInt(new DecimalFormat("#").format(Double.parseDouble("010.021")))
Output
10