This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 5 years ago.
So, assuming, for some reason, floats are absolutely required in the programme one is creating despite the inaccuracy regarding decimal points, is there any method one can use to round them to 2 decimal places without converting them into doubles?
Try this:
public static float roundFloat(float number, int scale)
{
int pow = 10;
for (int i = 1; i < scale; ++i)
pow *= 10;
float tmp = number * pow;
return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
Solid and fast.
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 1 year ago.
I understand double as a variable type but in line 4 it might be used as datatype conversion. I just don't get the double used in line 6, am I completely missing the point here?
public static void main(String args[]) {
int discountPercentage = 10;
double totalPrice = 800;
double priceAfterDiscount = totalPrice * (1 - ((double) discountPercentage / 100));
if (totalPrice > 500) {
priceAfterDiscount = priceAfterDiscount * (1 - ((double) 5 / 100));
}
System.out.println("Customer has paid a bill of amount: "+ priceAfterDiscount);
}
Writing 5 / 100 is an int division as both operand are ints, and in Java that will result in 0.
See Int division: Why is the result of 1/3 == 0?
To get 0.05, you need to make a division with double
define an operand as double explicitly
5.0 / 100
5 / 100.0
cast an operand
(double) 5 / 100
5 / (double) 100
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
How to divide 1 by 25(1/25) and get result .04 in java [duplicate]
(4 answers)
Closed 1 year ago.
I am trying to write a function to check a T score value and populate half of a 5x5 array.
public void calcTScores()
{
double temp = 0;
double tempSp = 0;
int n = 24;
this.tScores = new String [5][5];
for (int i = 0; i< this.Headers.length; i++){
for (int j = 0; j<this.Headers.length; j++)
{
if(i < j)
{
tempSp += (n-1)*this.SD[i] * this.SD[i] + (n-1)*this.SD[j] * this.SD[j];
tempSp = tempSp/(n+n-2);
tempSp = Math.sqrt(tempSp);
temp = tempSp * Math.sqrt(0.0833);
System.out.println(Math.sqrt(1/12));
temp = ((this.Mean[i] - this.Mean[j])/temp);
if(temp > 2.25 || temp< -2.25)
{
this.tScores[i][j] = "Y";
}
else
{
this.tScores[i][j] = "N";
}
temp = 0;
tempSp = 0;
}
}
}
}
Any idea why Math.sqrt(0.0833) and Math.sqrt(1/12) would evaluate to different values?
The T score when I add the 1/24 and 1/24 value and take the sqrt keeps evaluating to zero but when I plug in the actual decimal it gives me the answer I would expect
Any ideas why this is occuring?
1/12==0 as per integer division
There's nothing wrong with Math.sqrt. You're passing it the number zero.
Math.sqrt(1/12)
1/12 is a division operation on two integers (namely, 1 and 12), so it's going to produce an integer result. 12 goes into 1 zero times, so the integer result is zero. Thus, your expression is
Math.sqrt(0)
Consider
Math.sqrt(1.0/12.0)
Math.sqrt(1/12d)
Cast 1/12 to a double by casting one operand to a double.
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 2 years ago.
While I'm using truncating in this method, it is somewhere wrong as in picture
public static List<Double> interp(DoubleUnaryOperator f, double l, double u, int n) {
double d = (u - l)/n;
List<Double> result = new ArrayList<>(n);
double net = f.applyAsDouble(l);
result.add(net);
int i = 0;
while(i+1 < n){
result.add(Math.floor(f.applyAsDouble(l + d)*100)/100);
l += d;
i++;
}
return result;
}
Who know how to truncate correclty? P.S. its important for the number be in two decimal places.
Use this :
new DecimalFormat("#.##").format(dblVar);
df.setRoundingMode(RoundingMode.DOWN);
s = df.format(d);
and import the class java.text.DecimalFormat.
This question already has answers here:
Double division behaving wrongly
(4 answers)
Closed 7 years ago.
I have been trying for a few days to compute pi using the series expansion pi = 4(1-1/3+1/5-1/7... but whenever I use the code I have below, it returns 4.0.
public class Pi {
public static void main (String args[]) {
double pie = 0.0;
int max = 1000;
for (int x = 1 ; x < max ; x = x + 2) {
if (x % 4 == 1) {
pie+= 1/x;
} else if (x % 4 == 3) {
pie-=1/x;
}
}
System.out.println(4*pie);
}
}
In this, I am computing pie to a denominator below 1000. Pie is the variable that stores my value created for pie. At the end, it prints pi, but always returns 4.0.
Using the Debug feature in my IDE (Eclipse), I see the value of pie jumps to 4 from the initial value of 0, but then does not change for the rest of the times the program increments the value of x in the for loop, it does not do anything to pi.
You are performing integer division with 1/x, which always results in an int, truncating the true decimal value. 1/1 is 1, but 1 divided by anything larger is 0 in Java, so your result will always be 4.
Use a double literal to force floating-point division.
pie += 1.0 / x; // and pie -= 1.0 / x;
Alternatively, you can cast 1 to a double.
pie += (double) 1 / x; // and pie -= (double) 1 / x;
The problem is that you are performing integer division and adding the result to a double. x is an int and 1 is an int. When you divide an integer by an integer, you get back an integer. Hence what you're adding to pie is always an integer.
The first time you run the loop, you evaluate the expression 1/1, which returns just 1 (an integer) and assigns that value to pie. For everything else after, you get 0, which means that pie doesn't change. Hence when you finally print 4 * pie, you get 4.
There are a few options:
Use double everywhere.
Change pie += 1 / x; to pie += (1.0 / x); (and the same for the other one)
Cast 1 to double before adding to pie: pie += (double) 1 / x.
The problem is that you are making an integer division which returns less than zero. As an integer, the value will be rounded to zero instead. This adds zero to pie on each iteration.
What you need to do is to replace the literal integer ones, to literal floating point ones, like this
package cl.misc.pi;
public class Pi {
public static void main(String args[]) {
double pie = 0.0;
int max = 1000;
for (int x = 1; x < max; x = x + 2) {
if (x % 4 == 1) {
pie += 1.00 / x;
} else if (x % 4 == 3) {
pie -= 1.00 / x;
}
}
System.out.println(4 * pie);
}
}
As you see, I did replace pie += 1 / x for pie += 1.00 / x which now adds a floating point result to pie.
Result of this routine is 3.139592655589785
This question already has answers here:
Fahrenheit to Celsius conversion
(3 answers)
Closed 7 years ago.
I have to divide two integers and get a float as result
My Code:
Float ws;
int i = Client.getInstance().getUser().getGespielteSpiele() -Client.getInstance().getUser().getGewonneneSpiele();
int zahl1 = Client.getInstance().getUser().getGewonneneSpiele();
ws = new Float((zahl1 / i));
I check the values with the debugger
i = 64
zahl1 = 22
ws = 0.0
Why is the result of ws 0.0? What I should do to get the correct float?
When you divide two ints you perform integer division, which, in this case will result in 22/64 = 0. Only once this is done are you creating a float. And the float representation of 0 is 0.0. If you want to perform floating point division, you should cast before dividing:
ws = ((float) zahl1) / i;
zahl1 / i is computed as int division and then converted to Float by the Float constructor. For floating point division, cast one of the operands to float or double:
ws = new Float((float)zahl1 / i);
It's because you're doing integer division,you need to change the int value as float at first.
float ws = (float) zahl1 / i;
try:
float ws = (float)zahl1/i;