Java Float to "remove" comma - java

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;

Related

Calculate From different Double number

i have question about how to calculate from different double
for example
i have 3 type of double data
price (x, y, z)
1. Double type1 = 1.67876
2. Double type2 = 129.789
3.Double type3 = 1278.79
i want calculate like reduction all the double type using 10 for the 2digit last number after comma so for example
if after comma have 5digits the function will be
for example
Double returnX = type1-0.00010;
if after comma have 3digits the function will be
Double returnY = type2-0.010;
if after comma have 2digits the function will be
Double returnY = type3-0.10;
so how to make the logic for that ?
It may be implemented like this:
static double reduce(double x) {
double res = x;
String s = "" + x;
int posDot = s.indexOf(".");
if (posDot > -1) {
int fractionWidth = s.length() - posDot - 1;
double reduceAmount = 1;
while (fractionWidth-- > 1) {
reduceAmount *= 0.1;
}
res = x - reduceAmount;
}
return res;
}

Check if a double = 1/3

I have made a function that converts a double to a simplified fraction in Java:
public static int gcm(int a, int b) {
return b == 0 ? a : gcm(b, a % b);
}
public static String toFraction(double d) {
int decimals = String.valueOf(d).split("\\.")[1].length();
int mult = (int) Math.pow(10, decimals);
int numerator = (int) (d * mult);
int denominator = mult;
// now simplify
int gcm = gcm(numerator, denominator);
numerator /= gcm;
denominator /= gcm;
return numerator + "/" + denominator;
}
It works, except for the fact that if I use toFraction(1.0/3), this will, understandably, return "715827882/2147483647". How may I fix this to return "1/3"?
You have to allow for a certain error and not all fractions can be exactly represented as scalar values.
public static String toFraction(double d, double err) {
String s = Long.toString((long) d);
d -= (long) d;
if (d > err) {
for (int den = 2, max = (int) (1 / err); den < max; den++) {
long num = Math.round(d * den);
double d2 = (double) num / den;
if (Math.abs(d - d2) <= err)
return (s.equals("0") ? "" : s + " ") + num +"/"+den;
}
}
return s;
}
public static void main(String... args) {
System.out.println(toFraction(1.0/3, 1e-6));
System.out.println(toFraction(1.23456789, 1e-6));
System.out.println(toFraction(Math.E, 1e-6));
System.out.println(toFraction(Math.PI, 1e-6));
for (double d = 10; d < 1e15; d *= 10)
System.out.println(toFraction(Math.PI, 1.0 / d));
}
prints
1/3
1 19/81
2 719/1001
3 16/113
3 1/5
3 1/7
3 9/64
3 15/106
3 16/113
3 16/113
3 3423/24175
3 4543/32085
3 4687/33102
3 14093/99532
3 37576/265381
3 192583/1360120
3 244252/1725033
3 2635103/18610450
Note: this finds the 21/7, 333/106 and 355/113 approximations for PI.
No double value is equal to one third, so the only way your program can be made to print 1/3 is if you change the specification of the method to favour "nice" answers rather than the answer that is technically correct.
One thing you could do is choose a maximum denominator for the answers, say 100, and return the closest fraction with denominator 100 or less.
Here is how you could implement this using Java 8 streams:
public static String toFraction(double val) {
int b = IntStream.rangeClosed(1, 100)
.boxed()
.min(Comparator.comparingDouble(n -> Math.abs(val * n - Math.round(val * n))))
.get();
int a = (int) Math.round(val * b);
int h = gcm(a, b);
return a/h + "/" + b/h;
}
There is no nice approach to this. double is not very good for this sort of thing. Note that BigDecimal can't represent 1/3 either, so you'll have the same problem with that class.
There are nice ways to handle this but you will need to look at special cases. For example, if the numerator is 1 then the fraction is already reduced and you simply strip out the decimal places and return what you were given.

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.

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

Java- Get decimal at position n

What is the best way to get the decimal at position n from a float (by cutting out everything from the number except that decimal)?
It should work like this:
getDecimal(3.654987, 4) => returns 0.0009
getDecimal(3.654987, 2) => returns 0.05
Float f = new Float("0.123456789");
System.out.println(f.toString().charAt(5));
Prints 4. Try in this direction.
This should work for you:
public static double getDecimal(double num, int n) {
return ((int) (num * Math.pow(10, (double) n)) % 10) * Math.pow(10, (double) -n);
}
Assuming the position will be always a positive integer(> 0):
float input = 3.654987f;
int pos = 4;
String op = String.valueOf(input).replaceAll("\\d*\\.\\d{"+(pos-1)+"}(\\d)\\d+",
"0." + new String(new char[pos-1]).replace("\0", "0") + "$1");
System.out.println(op);

Categories