Rounding down a float number to 2 decimal points in java - java

I have a variable x that is 11.885, when I round this to 2 decimal points I want it to give me 11.88 but it won't work and I can't figure it out. I won't be using import or anything but just can't figure out a way to round this number down.
What I originally used:
double x = 11.885
double y = (double) Math.round(x * 100.0) / 100.0;
but this gives me 11.89. I also need this without printing it since I will be using this rounded number in my code.

Instead of Math.round(double), use Math.floor(double) like
double x = 11.885;
double y = Math.floor(x * 100) / 100.0;
System.out.println(y);
I get (as requested)
11.88

Try BigDecimal It has a lot of helpful features like this.
double x = 11.885;
BigDecimal y = BigDecimal.valueOf(x);
y.setScale(2, BigDecimal.ROUND_HALF_UP)

Related

Java decimal point in method

I am little bit lost with double decimal point at the moment.
I have basically two methods, which will set the values for double amount and double receive. Then another integer variable where I would like to set the (receive - amount) * 100.
For example if I have two double values and I want to set their difference to an int value, then would it be possible?
My problem is that if I try to find the difference between two values, then e.g. (10.0- 9.40), then it will be 0.599999999. How can I get 0.60 out of it inside the method and use it? I know how to use NumberFormat or DecimalFormat. Should I use one inside the method to set the number of decimal points?
you can round off the value im using a decimalformat to round off the number. You can pass a double variable inside the method and this will return a number rounded off to 2 decimal points.
double RoundTo2Decimals(double val) {
DecimalFormat df2 = new DecimalFormat("###.##");
return Double.valueOf(df2.format(val));
}
You can use BigDecimal to perform the rounding, or you can use maths like this. It basically multiplies by 100, rounds and divides by 100.
/**
* Performs a round which is accurate to within 1 ulp. i.e. for values very close to 0.5 it
* might be rounded up or down. This is a pragmatic choice for performance reasons as it is
* assumed you are not working on the edge of the precision of double.
*
* #param d value to round
* #return rounded value
*/
public static double round2(double d) {
final double factor = 1e2;
return d > WHOLE_NUMBER / factor || d < -WHOLE_NUMBER / factor ? d :
(long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor;
}
Easiest solution could be below. Modifications and improvements are welcomed.
double x =10.0;
double y =9.40;
int xy =0;
DecimalFormat df = new DecimalFormat("#.##");
xy = (int) (Double.valueOf(df.format(x-y))*100);
System.out.println(xy);
I think I figured it out by using Math.round().
I will just ask whether my solution is a good or a bad idea to use? I am not just so familiar with BigDecimal. Long story short about the code. Example inputs are as: a = 9.40 and b = 10.0
private int difference;
private double amountDue;
private double receive;
public void setAmount(double a) {
amountDue = a;
}
public void receive(double b) {
receive = b;
difference = (int)Math.round(100 * (receive - amount));
I just needed to get int difference as 0.60 * 100 = 60, but as I mentioned before then just calculating the difference caused 0.59999999.
Just an extra question. Is it ok for me to initialize int balance variable inside one method as I have done?

Cosine Law for inside angles

I'm trying to create a program in Java to calculate the inside angles of any triangle when the user inputs the side lengths. I've seen a few questions similar to this but I can`t get mine to work.
I want this to calculate the angle in degrees but it keeps giving me the wrong answer or not a number (NaN). I've tried putting it all in to one equation in case it was just rounding errors but it just gave the same answer. I've since put it back into this format to make it easier to read.
public class Triangles
{
// variables already declared and user inputs double sideOne, sideTwo, sideThree
threeSq=sideThree*sideThree;
twoSq=sideTwo*sideTwo;
oneSq=sideOne*sideOne;
public static double getAngleOne(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angOne;
angOne = (oneSq + twoSq - threeSq) / (2 * sideOne * sideTwo);
angOne = Math.toRadians(angOne);
angOne = Math.acos(angOne);
angOne = Math.toDegrees(angOne);
return angOne;
}
public static double getAngleTwo(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angTwo;
angTwo = (twoSq + threeSq - oneSq) / (2 * sideTwo * sideThree);
angTwo = Math.toRadians(angTwo);
angTwo = Math.acos(angTwo);
angTwo = Math.toDegrees(angTwo);
return angTwo;
}
public static double getAngleThree(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angThree;
angThree = (oneSq + threeSq - twoSq) / (2 * sideOne * sideThree);
angThree = Math.toRadians(angThree);
angThree = Math.acos(angThree);
angThree = Math.toDegrees(angThree);
return angThree;
}
}
I`m using the cosine law, but it is not giving me the correct answer. For example, when I input the side lengths as 3, 3 and 3 it gives me 71.68993312052173; when I input 5, 6 and 7 (sides 1, 2 and 3 respectively), I get NaN.
edit:
Thanks for the advice, I have changed all the ints to doubles and my math was the problem (forgot brackets around the oneSq + twoSq - threeSq)
I put up the full revised code but it is still giving the wrong answer, for a triangle with all sides the same, it should return 60 for all three but it`s returning 89.49999365358626.
After correcting the computation of the ratios there still remains one thing to do: Lose the lines
angOne = Math.toRadians(angOne);
at this point, angOne does not contain any angle. If the sides obey the triangle inequality, angOne should at that point contain a number between -1 and 1 that does not need converting.
The ratio of the areas for an equilateral triangle is 0.5. The operations convert-to-radians, acos, convert-to-degrees can be combined as
M*acos(x/M) = M*(pi/2-asin(x/M)),
with the multiplier M=180/pi. Since x/M is small, the result is approximately
M*(pi/2-x/M)=90-x,
resulting in a value close to 89.5, as obtained in your last trial.
Of course, the desired result is M*acos(0.5)=M*(pi/3)=60.
Apart from not using double values, your calculations are probably not correct.
According to cosine law
cosĪ³ = (a^2 + b^2 - c^2)/2ab
so change ang = oneSq + threeSq - twoSq / (2 * sideOne * sideThree); to
double ang = (oneSq + twoSq - threeSq)*1.0 / (2 * sideOne * sideTwo);

Rounding error with pi

I am trying to make a sequence of code that calculates the volume of a cone based on a user input height and radius (see below).
My problem is that the answer comes out wrong (but not by a long way). Using the example of height = 5, radius = 10, I get an answer from the code of 500 (treating pi as exactly 3), but calculating manually I get ~523.
I'm assuming it has something to do with the variable type I am declaring pi under (double then converting to long) but I have struggled to make any other combination of variable types work.
What is the correct version of this below that will store pi properly (to at least 5 or 6 dec places)?
double piDouble = Math.PI;
long height = Long.parseLong(heightString);
long pi = (new Double(piDouble)).longValue();
long radius = Long.parseLong(radiusString);
long volumeBase = (pi*(radius*radius)*height) / 3;
long pi = (new Double(piDouble)).longValue(); is a long, so it is equal to 3, exactly.
If you need more precision, use double all the way, and round at the end only. This should give you the result you expect:
double piDouble = Math.PI;
long height = Long.parseLong(heightString);
long radius = Long.parseLong(radiusString);
double volumeBase = (piDouble * (radius * radius) * height) / 3;
You can then round the result if you need to:
long roundedDownVolume = (long) volumeBase; //round down
long roundedVolume = Math.round(volumeBase); //or round to the closest long
You should use BigDecimal for this kind of arithmetic.

rounding decimal points [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Round a double to 2 significant figures after decimal point
I am trying to work with converting a decimal degree (23.1248) into a minutes style degree(23 7'29.3").
this is what I have so far:
double a=23.1248;
int deg=(int)a;//gives me the degree
float b=(float) (a-deg);
int min=(int) (b*60);//gives me the minutes
double sec= (double) ((c*60)-min);//gives me my seconds
everything works fine, but I would like to round the seconds up to either the nearest tenth or hundrenth. I have looked at decimal formatting, but would prefer not to cast it to a string. I have also looked at bigdecimal but do not think that would be helpful,
Try using Math.round(double) on the number after scaling it up, then scaling it back down.
double x = 1.234;
double y = Math.round(x * 100.0) / 100.0; // => 1.23
You can also use BigDecimal if you want to get really heavyweight:
BigDecimal a = new BigDecimal("1.234");
BigDecimal b = a.setScale(2, RoundingMode.DOWN); // => BigDecimal("1.23")
First off, there are library functions to do this, so why not just use those? See Math.round(). No need to reinvent the wheel. If you wanted to, though, you could try what follows. To round a double to the hundredth's place:
x = 0.01 * floor(x * 100.0)
To round a double to the tenth's place:
x = 0.1 * floor(x * 10.0)
To round a double to the 10^k place:
x = 10^k * floor(x / 10^k)
The implementation in any language - including Java - should be straightforward. A problem with this is that it doesn't really round, but truncates, to your position. To fix this, you can simply add 0.5 * 10^k to your number before rounding. If you just want to round up, use the versions above, and add 10^k before or after the computation.

Why does integer division code give the wrong answer? [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed last year.
I have a very simple division in Java (it's a product quantity / production per hour), however whenever I make this division I get strange errors:
float res = quantity / standard;
I have tried the above division with several values and I always get errors, however the one that I've tried everywhere else and gotten right was this:
Everywhere in the world:
13.6 = 6800 / 500;
Java:
13.0 = 6800 / 500;
I've researched BigDecimal and BigInteger, however I haven't found a way to create this division with them, is there any other way to do this division in Java without having precision errors??
Any help will be greatly appreciated.
You're dividing integers, which means that you're using integer division.
In integer division the fractional part of the result is thrown away.
Try the following:
float res = (float) quantity / standard;
^^^^^^^
The above forces the numerator to be treated as a float which in turn promotes the denominator to float as well, and a float-division is performed instead of an int-division.
Note that if you're dealing with literals, you can change
float f = 6800 / 500;
to include the f suffix to make the denominator a float:
float f = 6800f / 500;
^
If you concerned about precision I would suggest using double which has more than double the number of digits of precision. However floating point only accurately represents fractions which are a sum or powers of 0.5. This means 0.6 is only approximately represented. This doesn't have to be a problem with appropriate rounding.
double d = (double) 6800 / 500;
or
double d = 6800.0 / 500;
In my case I was doing this:
double a = (double) (MAX_BANDWIDTH_SHARED_MB/(qCount+1));
Instead of the "correct" :
double a = (double)MAX_BANDWIDTH_SHARED_MB/(qCount+1);
hi try this one it may help ful your requirement
double percent=(7819140000l-3805200000l)*100f/7819140000l;
public String format_Decimal(double decimalNumber) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(5);
nf.setMinimumFractionDigits(2);
nf.setRoundingMode(RoundingMode.HALF_UP);
String x = nf.format(decimalNumber);
return x;
}

Categories

Resources