I'm trying to convert a string "3.0" to int in java. I tried to convert using Integer.parseInt, but it throws an exception. Any idea how can I convert the string with decimal values to int in java and kotlin
String value = "3.0";
int i = Integer.parseInt(value);
In kotlin you can do this as
val str = "3.0"
val result = str.toDouble().toInt()
Convert the string to an integer, then parse:
int i = Integer.parseInt(str.replaceAll("\\..*", ""));
This removes the dot and everything after it, which is effectively what casting a floating point type to integer does.
String value = "3.0";
int i = (int) Float.parseFloat(value);
You can't parse "3.0" as an integer, because it represents a floating-point value. Your best bet is to parse it as such using the handy build-in functions (Double.parseDouble("3.0") or Float.parseFloat("3.0")) and then convert that to an integer.
How you convert it depends on how you want to treat the decimal portion
discard it (number moves closer to zero): cast to int
(int) 2.5 = 2, (int) -2.5 = -2
round it to the nearest integer: Math.round(), then cast*
(int) Math.round(2.5) = 3, (int) Math.round(-2.5) = -3
round to the higher integer (number moves towards positive infinity): Math.ceil() then cast
(int) Math.ceil(2.5) = 3, (int) Math.ceil(-2.5) = 2
round to the lower integer (number moves towards negative infinity):
Math.floor() then cast
(int) Math.floor(2.5) = 2, (int) Math.floor(-2.5) = -3
*Math.round takes either a float or a double, and produces an int or a long respectively, so you don't need cast to int if you use a float. All the other Math methods take doubles though, so I'm using that for consistency
Kotlin is the same, the equivalents are:
parse: "2.5".toDouble()
discard decimal: 2.5.toInt()
round to nearest: 2.5.roundToInt()
round to higher: ceil(2.5).toInt()
round to lower: floor(2.5).toInt()
(functions are in kotlin.math)
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
I'm having two float numbers, they can be decimals or not, depending on the operation I want to print the result either with decimal or without.
I'm using String.format to take off the decimal when not needed. However, I have trouble identifying when the result will be decimal. Tried the n1 % n2 > 0 method from a similar question, but when entering for example 6 + 7 the result becomes 13.0 instead of just 13.
Code so far:
float n1 = Float.parseFloat(request.getParameter("num1").toString().trim());
float n2 = Float.parseFloat(request.getParameter("num2").toString().trim());
String res = String.valueOf(n1+n2);
if(n1 % n2 > 0)
{
out.println("It's decimal");
out.println(n1+n2);
}else{
out.println(String.format("%.0f", n1+n2));
}
For doing exact math with non-integers (numbers with fractions) in Java you should use BigDecimal. This class allows for exact representation of non-integers of arbitrary precision.
That is your code should be changed to:
final BigDecimal n1 = new BigDecimal(request.getParameter("num1").toString().trim());
final BigDecimal n2 = new BigDecimal(request.getParameter("num2").toString().trim());
final BigDecimal res = n1.add(n2);
final BigDecimal remainder = n1.remainder(n2);
//if (res.stripTrailingZeros().scale() > 0) {
if (remainder.compareTo(BigDecimal.ZERO) != 0) {
System.out.println("It's decimal");
System.out.println(res);
} else {
final DecimalFormat df = new DecimalFormat("#.0f");
System.out.println(df.format(res));
}
The other answer will not give you the correct result, if a user inputs a number larger than Integer.MAX_VALUE or lower than Integer.MIN_VALUE. Casting to long will probably yield wrong results due to the precision of float that might cause the result to have a decimal fraction even if the input numbers did not...
However I hope you're doing some input validation of the request data. Otherwise you'll most likely get a lot of NumberFormatExceptions from your JSP-page.
UPDATE:
Updated the code example to check for scale instead of precision.
You can use Math.round to tell if a float is an integer. (There are other approaches if your only purpose is to suppress the decimal point for integers when formatting as a string--see KevinO's comment.)
If f is a float, Math.round(f) returns an int, which is f rounded to the nearest integer, unless f is outside the range of an int. However, if f is outside the range of an int, then f must be an integer, for all practical purposes--if f is large enough that it is too big to fit in an int, then it's too big to distinguish between values that are less than 1.0 apart (there are fewer bits of precision in a float than in an int). So there's no way for f to represent a non-integer of that magnitude.
Given that, and assuming that f isn't +/- infinity, you can test whether f is an integer like this:
public boolean isInteger(float f) {
return f > (float)Integer.MAX_VALUE ||
f < (float)Integer.MIN_VALUE ||
f == (float)Math.round(f);
}
But please note that even a non-integer could appear as something.000000 when you format it, since the formatter will have to round f to a certain number of decimal places when printing. It depends on what kind of format you're using.
NOTE: The above method is a correct way to determine whether a float is an integer, if the float is the only information you have. However, in the context of a larger program, there are other considerations. If the parameter string is "2000000000.1", when you parse it as a float you will get 2000000000, which is an integer, because the float doesn't have enough precision to represent the .1. At that point, your float will be an integer value, and it's too late for it to know about the .1--that information has been lost. If you don't want to lose that information, then don't use float or double--use BigDecimal instead.
Cast to int then back:
boolean isDecimal = myFloat != (float)(int)myFloat;
Casting to int truncates the decimal part.
Or, you can use a string approach. Decimals have non-zero digits after the dot, so:
boolean isDecimal = String.valueOf(myFloat).matches(".*\\.(?=.*[1-9]).*");
If you just need that for output, the easiest approach is probably to do this with string manipulation:
String s = String.format("%.4f", n1 + n2); // use whatever decimal places you like
s = s.replaceFirst("\\.0*$", "");
System.out.println(s);
This will fail if the decimal separator in your Locale is , instead of ., so be careful.
To really check if a double value x is integral you can use this test:
if (x % 1 == 0) {
// integral
} else {
// not integral
}
I'm trying to do some basic math and it keeps popping up as 0. I'm sure it has to do with it being an int but I don't know how to work around it. I need to use integers but the math to arrive at those integers uses decimals. How do I do it?
That's integer division.
To get non-integer results, use doubles instead.
This is not special to blackberry, it's standard java behaviour.
This is because you're doing integer math:
int subexpr1 = 14 / 20; // 0
int subexpr2 = subexpr1 * 100; // 0
Use a double instead or change the order
int expr1 = (int) 14.0/20 * 100; // Very small possibility of rounding errors
int expr2 = 14 * 100 / 20; // Will ignore fraction parts
You can change it to 14*100/20 - and then it will give what you want.
I.e. change the sequence of operations (14/20 is 0)
Your result is being cast as an int, so you are losing precision.
Try
double exp1 = 14/20.0*100;
i have an Integer value:
Integer value = 56472201;
Where the value could be positive or negative.
When I divide the value by 1000000, I want this result in the form 56.472201 but instead it gives me just the quotient. How am I able to get both the quotient and remainder values?
cast it to float and then do it:
int i = 56472201;
float j = ((float) i)/1000000.0
Edit: Due to precision(needed in your case), use double. Also as pointed by Konrad Rudolph, no need for explicit casting:
double j = i / 1000000.0;
You have to convert the value to a floating point type first, otherwise you will be doing an integer division.
Example in C#:
int value = 56472201;
double decimalValue = (double)value / 1000000.0;
(The cast is actually not needed in this code, as dividing by a floating point number will cast the value to match, but it's clearer to write out the cast in the code as that is what actually happens.)
If you divide an int by a double you will be left with a double result as illustrated by this unit test.
#Test
public void testIntToDouble() throws Exception {
final int x = 56472201;
Assert.assertEquals(56.472201, x / 1e6d);
}
1e6d is 1 * 10^6 represented as a double
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