How to get the value which is after the point - java

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.

Related

Make advanced number calculations? 2.1k equal to 2100 etc..?

So as the title says, if the input for example was 2.1k it should equal to 2100, if it was 3.7k it would be 3700 and so on. I have some code as following, I haven't really tried anything, just thinking about how the formula could be:
String arg = args[0];
if(arg.contains("k")) {
args[0].replace("k", "000");
}
You could check if the arg ends with "k", if it does parse the double value preceeding every character before "K" and multiply by 1000. Something like
String arg = "2.1k";
if (arg.endsWith("k")) {
int val = (int) (Double.parseDouble(arg.substring(0, arg.length() - 1))
* 1000);
arg = String.valueOf(val);
}
System.out.println(arg);
Outputs
2100
For the k example it would be:
int count = StringUtils.countMatches(arg, "k");//count the amount of k's
double decNumber = Double.parseDouble(arg.replace("k", "");//removes all k's and parse to a double
double finalNumber = decNumber * Math.pow(1000, k);//multiple by 1000^k
This works for any amount of k's AFTER the decimal number.
The correct way to do this looks more like:
String arg = args[0];
if(arg.contains("k")) {
newVal = args[0].replace("k", ""); //just drop the K and be left with a decimal
newVal = parseInt(args[0] * 1000); //New value is whatever was passed in times 1000
}

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;

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;

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

Use DecimalFormat to get varying amount of decimal places

So I want to use the Decimal Format class to round numbers:
double value = 10.555;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println(fmt.format(value));
Here, the variable value would be rounded to 2 decimal places, because there are two #s. However, I want to round value to an unknown amount of decimal places, indicated by a separate integer called numPlaces. Is there a way I could accomplish this by using the Decimal Formatter?
e.g. If numPlaces = 3 and value = 10.555, value needs to be rounded to 3 decimal places
Create a method to generate a certain number of # to a string, like so:
public static String generateNumberSigns(int n) {
String s = "";
for (int i = 0; i < n; i++) {
s += "#";
}
return s;
}
And then use that method to generate a string to pass to the DecimalFormat class:
double value = 1234.567890;
int numPlaces = 5;
String numberSigns = generateNumberSigns(numPlaces);
DecimalFormat fmt = new DecimalFormat ("0." + numberSigns);
System.out.println(fmt.format(value));
OR simply do it all at once without a method:
double value = 1234.567890;
int numPlaces = 5;
String numberSigns = "";
for (int i = 0; i < numPlaces; i++) {
numberSigns += "#";
}
DecimalFormat fmt = new DecimalFormat ("0." + numberSigns);
System.out.println(fmt.format(value));
If you don't need the DecimalFormat for any other purpose, a simpler solution is to use String.format or PrintStream.format and generate the format string in a similar manner to Mike Yaworski's solution.
int precision = 4; // example
String formatString = "%." + precision + "f";
double value = 7.45834975; // example
System.out.format(formatString, value); // output = 7.4583
How about this?
double value = 10.5555123412341;
int numPlaces = 5;
String format = "0.";
for (int i = 0; i < numPlaces; i++){
format+="#";
}
DecimalFormat fmt = new DecimalFormat(format);
System.out.println(fmt.format(value));
If you're not absolutely bound to use DecimalFormat, you could use BigDecimal.round() for this in conjunction with MathContext of the precision that you want, then just BigDecimal.toString().

Categories