split float in Java Android - java

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);

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.

Java Float to "remove" comma

I need to convert a float to an int, as if the comma was removed.
Example:
23.2343f -> 232343
private static int removeComma(float value)
{
for (int i = 0; ; i++) {
if((value * (float)Math.pow(10, i)) % 1.0f == 0.0f)
return (int)(value * Math.pow(10, i));
}
}
The problem is with rounding up of the number. For example if I pass 23000.2359f it becomes 23000236, because it rounded up the input to 23000.236.
Java float doesn't have that much precision, which you can see with
float f = 23000.2359f;
System.out.println(f);
which outputs
23000.236
To get the output you want, you could use a double like
double d = 23000.2359;
String v = String.valueOf(d).replace(".", "");
int val = Integer.parseInt(v);
System.out.println(val);
Output is (the requested)
230002359
you must find a way to get the number of digit after decimal place 1st. Suppose it is n. then multiply the number with 10 times n
double d= 234.12413;
String text = Double.toString(Math.abs(d));
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;

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.

Convert "0.25000%" to double in 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;

How to round double to nearest whole number and return it as Integer

Let suppose that I have double x. I would return nearest whole number of x. For example:
if x = 6.001 I would return 6
if x = 5.999 I would return 6
I suppose that I should use Math.ceil and Math.floor functions. But I don't know how return nearest whole number...
For your example, it seems that you want to use Math.rint(). It will return the closest integer value given a double.
int valueX = (int) Math.rint(x);
int valueY = (int) Math.rint(y);
public static void main(String[] args) {
double x = 6.001;
double y = 5.999;
System.out.println(Math.round(x)); //outputs 6
System.out.println(Math.round(y)); //outputs 6
}
The simplest method you get taught in most basic computer science classes is probably to add 0.5 (or subtract it, if your double is below 0) and simply cast it to int.
// for the simple case
double someDouble = 6.0001;
int someInt = (int) (someDouble + 0.5);
// negative case
double negativeDouble = -5.6;
int negativeInt = (int) (negativeDouble - 0.5);
// general case
double unknownDouble = (Math.random() - 0.5) * 10;
int unknownInt = (int) (unknownDouble + (unknownDouble < 0? -0.5 : 0.5));
int a = (int) Math.round(doubleVar);
This will round it and cast it to an int.
System.out.print(Math.round(totalCost));
Simple
Math.round() method in Java returns the closed int or long as per the argument
Math.round(0.48) = 0
Math.round(85.6) = 86
Similarly,
Math.ceil gives the smallest integer as per the argument.
Math.round(0.48) = 0
Math.round(85.6) = 85
Math.floor gives the largest integer as per the argument.
Math.round(0.48) = 1
Math.round(85.6) = 86

Categories