Arithmetic Operations on String And Casting - java

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)

Related

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 formatting potential string doubles or integer into integers

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-

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.

How to do an Integer.parseInt() for a decimal number?

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

Categories

Resources