Convert "0.25000%" to double in java - java

Please help to convert the string value ("0.25000%") to double value.
0.25000% = 0.0025 (need to get this value as double)
String num = "0.25000%";
double d = Double.parseDouble(num);//does not work

You can try this
String num = "0.25000%";
double d = Double.parseDouble(num.replace("%","")); // remove %
System.out.println(d);
Out put:
0.25
For your edit:
You can divide final answer by 100
System.out.println(d/100);
Now out put:
0.0025

String num = "0.25000%";
BigDecimal d = new BigDecimal(num .trim().replace("%","")).divide(BigDecimal.valueOf(100));//no problem BigDecimal
this can convert for decimal.

Remove the % character and divide by 100
String num = "0.25000%";
double d = Double.parseDouble(num.replace("%","")) / 100;

Related

Setting 2 decimal places in double value in Java

I get the values from the j table. I want to show cost in 2 decimal places and qty in no decimal places.
Currently both outputs one decimal place(123.0)
How to fix this;
DecimalFormat df= new DecimalFormat("0.00");
int i = tableSale.getRowCount();
String id = (String) tableSale.getValueAt(i-1, 0);
String name = (String) tableSale.getValueAt(i-1, 1);
double dcost = (double) tableSale.getValueAt(i-1, 2);
double cst=Double.valueOf(df.format(dcost));//setting 2 decimal places
String cost = String.valueOf(cst);//converting double to string
double dqty = (double) tableSale.getValueAt(i-1, 3);
DecimalFormat dd=new DecimalFormat("0");
double qt = Double.valueOf(dd.format(dqty));
String qty = String.valueOf(dqty);//converting double to string
double ditemDiscount = (double) tableSale.getValueAt(i-1, 4);
String itemDiscount = String.valueOf(ditemDiscount);//converting double to string
double dgrossTotal = (double) tableSale.getValueAt(i-1, 5);
double gTotal=Double.valueOf(df.format(dgrossTotal));//setting 2 decimal places
String grossTotal = String.valueOf(gTotal);//converting double to string
I think you can use this:
double dcost = (double) tableSale.getValueAt(i-1, 2);
String text = new DecimalFormat("##.##").format(dcost);
For the same with the rest double values.
Hope this help!
double d;
System.out.printf(".2f",d);
For costs I would advise against double. Use BigDecimal instead.
As for the formatting:
String.format("%.2d", dcost); and String.format("%.0d", qty); can be used.
try
String.format("%.2f", 123.0) //for two decimal point.
and
String.format("%.0f", 123.0)// for no decimal point.
output:
123.00
123
If you want to round to 2 decimal places you can use this function.
double dcost = round2(tableSale.getValueAt(i-1, 2));
This avoids the overhead of formatting a string just so you can parse it.
private static final double WHOLE_NUMBER = 1L << 53;
public static double round2(double d) {
final double factor = 1e2;
return d > WHOLE_NUMBER || d < -WHOLE_NUMBER ? d :
(long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}
You can adjust the factor to taste.

What types to use for my numbers when calculating

So I need to calculate a value.
The input I get is this:
a is seed/m2. The value might a for example 56 but it might be 56.7 also.
b is in g's. for instance 600g
c is % value, might be 90.6 also
d is % value, might be 90.6 also
The result I get should be as kg/ha
Regular int does not cut it. The value of (56 * 600 / 100 / 100) / 100
will be 0.0336. I could multiply it with 10000 but I would lose the precision.
I also tried BigDecimal for this but it gave me a ArithmeticException: “Non-terminating decimal expansion; no exact representable decimal result” when I changed the values of my % variables to something else than 100.
What would be the best option to go with this? The calculation was easy to do in exel as it knew how to convert each value automatically, but doing it in Java code is another thing.
My solutions:
int version:
int a = Integer.decode(germinativeSeed.getText().toString());
int b = Integer.decode(seedMass.getText().toString());
int c = Integer.decode(clean.getText().toString());
int d = Integer.decode(germinative.getText().toString());
int result2 = ( a * b / c / d) / 100;
result is 0
BigDecimal solution:
BigDecimal result2;
BigDecimal a = new BigDecimal(germinativeSeed.getText().toString());
BigDecimal b = new BigDecimal(seedMass.getText().toString());
BigDecimal c;
BigDecimal d;
if (clean.getText().toString().equals("")) {
c = new BigDecimal("100");
} else {
c = new BigDecimal(clean.getText().toString());
}
if (germinative.getText().toString().equals("")) {
d = new BigDecimal("100");
} else {
d = new BigDecimal(germinative.getText().toString());
}
BigDecimal hundred = new BigDecimal("100");
BigDecimal test = new BigDecimal("10000");
result2 = a.multiply(b);
result2 = result2.divide(c, 2, RoundingMode.HALF_UP);
result2 = result2.divide(d, 2, RoundingMode.HALF_UP);
result2 = result2.divide(hundred, 2, RoundingMode.HALF_UP);
result2 = result2.multiply(test);
Result is correct with this only if % values are 100%.
double seed = (double) seedInput;
double m2 = (double) m2Input;
double b = (double) bInput; // unit 'g' is not relevant
double c = (double) cInput;
double d = (double) dInput;
double a = seed / m2;
int result2 = ( a * b / c / d) / 100.0;
So I converted everything to double so you won't have problems with implicit conversions to int.
Your problem comes when you have rational numbers like 1/3, this cannot be represented in a bigdecimal, as it has an infinite representation.
If you really need very big precision you should crate a new bigrational class, where you would store a nominator and denominator, and calculate with them. The code would be much mode complicated.
If you don't need that go for doubles.
Try using float or double (preferred double because of the precision).

How to get the value which is after the point

How to get the value which is after the point.
Example:
If 5.4 is the value and I want to get the value 4 not 0.4, how can I do this?
You can use String functions for that :
public static void main(String args[]){
Double d = 5.14;
String afterD = String.valueOf(d);
afterD =afterD.substring(afterD.indexOf(".") + 1);
System.out.println(afterD);
}
first of all convert number to String,
Then using Substring get indexof(".") + 1 then print it.
& see it ll work.
OR You can try :
double d = 4.24;
BigDecimal bd = new BigDecimal(( d - Math.floor( d )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.intValue() );
will print : 24
suppose your input is 4.241 then you have to add 1 extra 0 in BigDecimal bd formula i.e. instead of 100 it ll be 1000.
Code:
double i = 5.4;
String[] s = Double.toString(i).split("\\.");
System.out.println(s[1]);
output:
4
Explantion:
you can convert the double to String type and after that use split function which split the converted double to String in two pieces because of using \\. delimiter. At the end, type out the second portion that you want.
you can try this
code:
double i = 4.4;
String s = Double.toString(i);
boolean seenFloatingPoint = false;
for (int j = 0; j < s.length(); j++) {
if(s.charAt(j)== '.' && !seenFloatingPoint){
seenFloatingPoint = true;
} else if (seenFloatingPoint)
System.out.print(s.charAt(j));
}
System.out.println("");
output:
4
the one line answer is
int floatingpoint(float floating){
return Integer.valueOf((Float.toString(floating).split(".")[1]));
}
which will do as follows:
convert the number e.g 56.45 to string
then split the string in string array where [0]="56" and [1]="45"
then it will convert the the second string into integer.
Thanks.
Try this way
Double d = 5.14;
String afterD = String.valueOf(d);
String fractionPart = afterD.split("\\.")[1];
Try this way
double d = 5.24;
int i = Integer.parseInt(Double.toString(d).split("\\.")[1]);
int i=(int)yourvalue;
float/double afterDecimal= yourvalue - i;
int finalValue = afterDecimal * precision;//define precision as power of 10
EX. yourvalue = 2.345;
int i=(int)yourvalue;//i=2
float/double afterDecimal= yourvalue - i;//afterDecimal=0.345
int finalValue = afterDecimal * precision;
//finalValue=0.345*10 or
//finalValue=0.345*100 or
// finalValue=0.345*1000
...
System.out.println((int)(5.4%((int)5.4)*10));
Basically 5.4 mod 5 gets you .4 * 10 gets you 4.

split float in Java Android

I have a number like 2.75. I want to split this number into two other floats. Here is an example of what I am searching for:
value = 2.75
value2 = 2.0
value3 = 0.75
I need them in my algorithm, so how could I implement this? I found split() but it returns string. I need floats or integer at least.
You could cast
float value = 2.75f;
int valueTruncated = (int) value;
float value2 = valueTruncated;
float value3 = value - value2;
You can also try this
double value = 2.75;
double fraction=value%1;//Give you 0.75 as remainder
int integer=(int)value;//give you 2 fraction part will be removed
NOTE:
As result may very in fraction due to use of double.You better use
float fraction=(float) (value%1);
if fractional part is big.
Another option is to use split():
double value = 2.75;
/* This won't work */// String[] strValues = String.valueOf(value).split(".");
String[] strValues = String.valueOf(value).split("\\.");
double val1 = Double.parseDouble(strValues[0]); // 2.0
double val2 = Double.parseDouble(strValues[1]); // 0.75
if the input is 59.38
result is
n1 = 59
n2 = 38
this is what I came up with:
int n1, n2 = 0;
Scanner scan = new Scanner(System.in);
double input = scan.nextDouble();
n1 = (int) input;
n2 = (int) Math.round((input % 1) * 100);

java program using int and double

I have written a simple Java program as shown here:
public class Test {
public static void main(String[] args) {
int i1 =2;
int i2=5;
double d = 3 + i1/i2 +2;
System.out.println(d);
}
}
Since variable d is declared as double I am expecting the result of this program is 5.4 but I got the output as 5.0
Please help me in understanding this.
i1/i2 will be 0. Since i1 and i2 are both integers.
If you have int1/int2, if the answer is not a perfect integer, the digits after the decimal point will be removed. In your case, 2/5 is 0.4, so you'll get 0.
You can cast i1 or i2 to double (the other will be implicitly converted)
double d = 3 + (double)i1/i2 +2;
i1/i2 when converted to int gives 0. ie. why you are getting 5.0. Try this :
public static void main(String args[])
{
int i1 =2;
int i2=5;
double d = 3 + (double)i1/(double)i2 +2;
System.out.println(d);
}
This line is done in parts:
double d = 3 + i1/i2 +2;
double d = 3 + (i1/i2) +2;
double d = 3 + ((int)2/(int)3) +2;
double d = 3 + ((int)0) +2;
double d = (int)5;
double d = 5;
The double just means that the answer will be cast to a double, it doesn't have any effect till the answer is computed. You should write
double d = 3d + (double)i1/i2 +2d; //having one double in each "part" of the calculation will force it to use double maths, 3d and 2d are optional
i1/i2 will be 0 because both i1 and 12 are integers.
if you cast i1 or i2 to double then it will give the desired output.
double d = 3 + (double)i1/i2 +2;
This link provides information about data type conversion, both implicit and explicit type.
To provide exact answer to the question will be :
double d = 3 + (double)i1/i2 + 2
int i1 =2;
int i2=5;
double d = 3 + (double)i1/(double)i2 +2;
if i1/i2 will be fractional value then double will help it to be in fraction instead of int.
so now you will the result as you want. or you can also use following code
double d = 3+(double)i1/i2+2;
In this line i1 is converted into double which will be divided with i2 and result will be in double, so again result will be as 5.4
Since i1=2 and i2=5 are integer type and when you divide (2/5) them, It gives integer value (0) because fractional part(.4) get discarded.
So put (double)i1/i2 on the equation.

Categories