String formatting potential string doubles or integer into integers - java

I receive a string from a server that sometimes is a double and sometimes is an integer. And i need it to be an integer.
When i do a Integer.parseInt(confusedStringNumber)
If its a double, it throws a Number format exception. Is there a way to format the string to drop all decimal places whether they exist or not ? Thanks

int i = (int)Float.parseFloat("1.0");
int j = Float.valueOf("1.0").intValue();

Refer to the following types and methods which can give you what you're asking for:
https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#round-java.math.MathContext-

Related

Arithmetic Operations on String And Casting

I am writing a java code on android studio and I want to do an operation for making a discount percentage to a number that is taken from the edit text as a string and it should be a double or int to use arithmetic operations on it so help me please find the way to solve it.
I am assuming that you want to convert the string to int or double.
String number = editText.getText().toString();
just write,
int n = Integer.parseInt(number);
now you can use n variable as you want.
percentage values are always floating numbers. for that an integer is not going to work well..
try instead a float or a double...
and use a widget that you can set/get without a string convertion, in that way you will avoid pains in the neck with Locale ways to represent those numbers...(is 13.5% the same as 13,5%?) etc
something like:
String x = editText.getText().toString();
just write:
double n = Double.parseDouble(x);
here the doc:
https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)

Number Format Exception Errors

I get this error whenever I run my program:
Exception in thread "main" java.lang.NumberFormatException: For input string: "9999997560"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:461)
at java.lang.Integer.valueOf(Integer.java:554)
at jsobcpuburnerpd3.Main.main(Main.java:22)
Java Result: 1
The program has two do-while loops that are nearly identical, and the first works perfectly. I only have problems with the second one.
BigDecimal lower = new BigDecimal("1000001520");
BigDecimal upper = new BigDecimal("9999997560");
int var = 2520;
String strL = lower.toString();
Integer intL = Integer.valueOf(strL);
String strU = upper.toString();
Integer intU = Integer.valueOf(strU);
Both numbers have the same amount of digits, and are converted to Integer the same way. Both are handled nearly the same way in the loops.
intL = intL + var;
intU = intU - var;
I have also attempted this without converting from BigDecimal to String, and inputting the number directly to String, but still got the same error.
EDIT I am using BigDecimal because it's a part of what my teacher wanted us to use in our work. I know it's not needed.
Obviously you will get a number format exception because the maximum value that can be store in an Integer is 2,147,483,647 which is less than 9,999,997,560.
On the other hand 1,000,001,520 is less than 2,147,483,647 which is why that works fine.
(Edit Based on Tunaki's suggestion) FYI - Moreover you really don't have to use a BigDecimal because it seems that the only reason you need it is to convert it to an Integer. So it is not required.
Also an Integer is not required because you don't seem to be requiring a reference type and hence the primitive type int should be apt. Moreover in your for loop you are adding and subtracting values from Integer which will lead to unnecessary boxing and unboxing and will be very inefficient. So use the primitive type int which would be better.
Convert the BigInteger to Integer using intValue() Method
BigDecimal lower = new BigDecimal("1000001520");
BigDecimal upper = new BigDecimal("9999997560");
Integer intBL = lower.intValue();
Integer intBU = upper.intValue();

Finding number of digits before a decimal point in java

I have declared the variable for the double I'm using:
z= 345.876;
Now I want to display the number of digits that come before the decimal point. I tried to do the following:
String string_form = new Double(z).toString().subString(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);
I get an error saying: 'The method subString(int, int) is undefined for the type String'
Then a quick fix shows to change it small case s as: substring. However the error then changes to the string, 'string_form' which says it's not initialized. Any ideas on what to do?
And also how would I modify that to find the number of digits that come after a number? I know in the part
.indexOf('.')
I'd replace the decimal point with a number but how would i change it so that it displays how many digits come AFTER the number, not before? thanks. and yes I have imported the decimalformat text lang.
You're trying to use string_form before you have actually created it.
If you break
String string_form = new Double(z).toString().substring(0,string_form.indexOf('.'));
double t = Double.valueOf(string_form);
into
String string_temp = new Double(z).toString();
String string_form = string_temp.substring(0,string_temp.indexOf('.'));
double t = Double.valueOf(string_form);
Then it should work.
To get the numbers after the decimal point just take the digits from period until the end of the number.
String string_temp = new Double(z).toString();
String string_form = string_temp.substring(string_temp.indexOf('.'), string_temp.length());
double t = Double.valueOf(string_form);
As others have pointed out though, there are many better ways than converting to string and checking for period and reconverting.
The number of decimal digits before the decimal point is given by
(int)Math.log10(z)+1
The number of decimal digits after it is imprecise and depends on how much precision you use when converting to decimal. Floating-point values don't have decimal places, they have binary places, and the two are incommensurable.
just convert the double to a string. find the index of . with indexOf. get the length of the string. subtract the index of . from the length and you should have the count.
String string_form = Double(z).toString();
int index = string_form.indexOf('.');
double d = Double.parse(string_form.substring(0, index+1));
If the numbers are small, you could try
int i = (int) z;
or
long l = Math.round(z);
You're using string_form in the expression string_form.indexOf('.'), but it's not initialized yet, because it's only set after the call to substring(). You need to store the value of toString() in a temporary variable so you can access it in the call to substring(). Something like this
String stringForm = new Double(z).toString();
stringForm = stringForm.substring(stringForm.indexOf('.'));
There are other and better ways to do this, however. Math.floor(z) or even just a cast (long)z will work.
Could do this, for examble:
Integer.parseInt(String.valueOf(possibleBirths).split(".")[0]);
You can do the next thing:
Double z = 345.876;
int a = t.intValue();
int counter = 0;
while(a != 0) {
counter++;
a = a / 10; }
System.out.println(counter);

Changing a String decimal (2.9) to Int or Long issues

Okay, I'm fairly new to java but I'm learning quickly(hopefully). So anyway here is my problem:
I have a string(For example we will use 2.9), I need to change this to either int or long or something similar that I can use to compare to another number.
As far as I know int doesn't support decimals, I'm not sure if long does either? If not I need to know what does support decimals.
This is the error: java.lang.NumberFormatException: For input string: "2.9" with both Interger.parseInt and Long.parseLong
So any help would be appreciated!
You can't directly get int (or) long from decimal point value.
One approach is:
First get a double value and then get int (or) long.
Example:
int temp = Double.valueOf("20.2").intValue();
System.out.println(temp);
output:
20
int and long are both integer datatypes, 32-bit and 64-bit respectively. You can use float or double to represent floating point numbers.
That string (2.9) is neither integer nor long. You should use some decimal point types, for example float or double.
Both int and long are integer values (being long the representation of a long integer that is an integer with a higher capacity). The parsing fails because those types do not support a decimal part.
If you were to use them and enforce a casting you're relinquishing the decimal part of the number.
double iAmADouble = 100 / 3;
int iWasADouble = (int)iAmADouble; //This number turns out to be 33
Use double or float instead.

Converting a String that contains decimal to Long

I have following sample (link to ideone).
long lDurationMillis = 0;
lDurationMillis = Long.parseLong("30000.1");
System.out.print("Play Duration:" + lDurationMillis);
It throws an exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "30000.1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:419)
at java.lang.Long.parseLong(Long.java:468)
at Main.main(Main.java:9)
But why it wont let me convert that number to a string directly ?I can convert number to integer and than convert to double . But is there any other way ?
The value 30000.1 is an invalid long value. You could parse the double value first:
lDurationMillis = (long)Double.parseDouble("30000.1");
You could use BigDecimal in this case:
BigDecimal bd = new BigDecimal("30000.1");
long l = bd.setScale(0, BigDecimal.ROUND_HALF_UP).longValue();
System.out.println(l);
The title says converting string to long, first question is about coverting number to string, next statement about converting number to integer to string. I am confuse.
But for anything to do with floating points, I have to point you at obligatory reference What Every Computer Scientist Should Know About Floating-Point Arithmetic .
In java, int and long do not have fractional parts, so a string like 3000.1 cannot be covnerted to one of these. It can be converted to float or double but if you read the above article you will realize that the coversion can be lossy, i.e. if you canvert that double back to a String you may not get the original 3000.1 back. It will be something close, for appropriate defintion of close, but may not be same.
If you want to use exact precision then BigDecimal is your friend. It will be much slower then the number types, but it will be precise.
Because long can't have fractional part, you could convert it to double and then cast it to long ignoring fractional part
You can do NumberFormat handling as below :
long lDurationMillis = 0;
try{
NumberFormat nf = NumberFormat.getInstance();
lDurationMillis = nf.parse("30000.1").longValue();
System.out.print("Play Duration:" + lDurationMillis);
}catch(ParseException e)
{
e.printStackTrace();
}
Output:
Play Duration:30000

Categories

Resources