Rounding off result in java - java

Hello i am making a program that computes the frequency distribution and i have a problem in getting the number of class because I am going to use this in frequency distribution... the result of # of class is...
6.286797971382275 and it is correct but...
i want to round this off to 7...
how am i going to do that? thanks
String []values = ( inputValues.getText().toString().split(","));
int[] convertedValues = new int[values.length];
txtTotalNum.setText(Integer.toString(values.length));
//calculate for the minimum and maximum number
Arrays.sort(convertedValues);
int max=convertedValues[0];
for(int i=0;i<convertedValues.length;i++){
convertedValues[i] =Integer.parseInt(values[i]);
if(convertedValues[i]>max){
max=convertedValues[i];
}
}
int min = convertedValues[0];
double classes=0;
for(int i=0;i<convertedValues.length;i++){
convertedValues[i] =Integer.parseInt(values[i]);
if(convertedValues[i]<min){
min=convertedValues[i];
}
}
txtMinimum.setText(Integer.toString(min));
txtMaximum.setText(Integer.toString(max));
//calculate for the range
int range=max - min;
txtRange.setText(Integer.toString(range));
//calculate for the # of classes
classes=1+3.3*Math.log10(convertedValues.length);
Classes.setText(Double.toString(classes));

Use Math.ceil()
Math.ceil(6.286797971382275);
This is what it is going to return you,
The smallest (closest to negative infinity) floating-point value that
is greater than or equal to the argument and is equal to a
mathematical integer.
Read the API before using it.

Consider the Math class.
Math.ceil()

Simply use Math.ceil(). It will round up your number to the nearest whole value. Note, it still returns a double.

Use below code.
double dval = 6.286797971382275 ;
System.out.println(dval);
System.out.println(Math.ceil((dval)));

You can use DecimalFormat beside Math.ceil()
double input = 6.286797971382275;
DecimalFormat df = new DecimalFormat("#");
df.setRoundingMode(RoundingMode.UP);
String output = df.format(input);
System.out.println("output : " + output);

Related

Java- Rounding up anything after 2 decimal points *Not just %.2f*

So as the top says. I am stuck on a rather simple problem but its seems I am stuck.
Example:
x = 3.141
When I use printf("x is: %.2f", x);
it spits out: X is 3.14
Well to calculate state tax anything above a cent needs to be rounded up so 3.141 should be 3.15. Is there a simple printf I can modify or an additional tag I can add? Or will I need to go a round about way to calculate the additional bit?
The easiest thing would be to add 0.005 to the number.
PS: Make sure you calculate everything strictly in BigDecimal. Using double for money is not recommended.
Instead of using printf, use a DecimalFormat with RoundingMode.CEILING:
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
String rounded = df.format(x)
System.out.printf("x is: %s", rounded);
Math.ceil(x * 100) * 0.01
Avoids magic rounding numbers (do you need to add 0.9, or 0.99, or 0.999, etc)
This is a possible solution:
public static float roundUp(float num, int positions) {
int tmp = ((int)(num*Math.pow(10, positions)));
tmp = tmp + 10 - tmp%10;
return ((float)(tmp/Math.pow(10, positions)));
}
You can obtain what you want by calling
roundUp(num, 3);
Or if you want a less-generic method, you can as well use:
public static float roundUp(float num) {
int tmp = ((int)(num*1000.0f));
tmp = tmp + 10 - tmp%10;
return ((float)(tmp/1000.0f));
}

Rounding With Arrays

massTotal is printing out as a number ending in ".0" no matter what the decimal should be. The massCounter[] indexes are doubles. How do I make it round to the first decimal place, instead of to the whole number?
public static double massTotal(double[] massCounter) {
double massTotal = 0.0;
for (int i = 0; i < massCounter.length; i++) {
massTotal += Math.round(massCounter[i] * 10.0 / 10.0);
}
return massTotal;
}
Thanks!
Your Math.round function is basically rounding everything, i.e.
1.5 -> 2
22.4 -> 22
So therefore when they all get totalled in the method, it will always be x.0, which is just printing a whole number as a double, showing the first .0.
What you could do, is to completely remove the Math.round and then print the result with using String.format and it will show you the output with one decimal place.
String.format("%.1f", massTotal(myArray))
Or even easier, if you are allowed to use Java8 capabalities:
double total = DoubleStream.of(myArray).sum();
System.out.println(String.format("%.1f", total));
Online example

In Java how does one convert from declared int value then print out decimal approximations

This is to say that the int are put into a System.out.println(); method that divides them up. But the value is a whole number, how does one take what's outputted as a whole number and get a decimal value from the declare int values?
Thank you
Well there's a couple ways, but you just cast it:
int myInt = 42;
System.out.println((double) myInt);
//Formatter
System.out.printf("%.2f\n", (double) myInt); //control output, e.g. 2 decimal places
I believe the problem is that you have two integer values and you want to merge them to become one number, with one of the 2 integers in the decimal part?
Well, if that is your question, then you can solve it by a simple while loop.
double wholePart = (double) userInput;
double decimalPart = (double) userInput;
while(Math.abs(decimalPart)>=1)
decimalPart /= 10;
System.out.print(Math.sign(decimalPart * wholePart) (Math.abs(wholePart) + Math.abs(decimalPart)));
Edit2: Using absolute values

how to make Math.random round to a number

I am making a lottery type game and using Math.random() for the numbers. I want it to always print out what number you got in relation to 0 - 100 (so if Math.random outputted 0.03454 and the number to win was below 0.05, it would set the text of a label to 5). How would you make it round to just a 0.00 number?
Here is some of the code if you want to see what I mean.
public void lotterymath()
{
double x = Math.random();
System.out.println(x);
if (x <= 0.02)
output.setText("you win " + x);
else
output.setText( "you lost " + x);
}
I also have a button below that calls lotterymath() by the way :)
Edit: misread original post:
You will want to multiply by 100, and then cast to an int to truncate it, or Math.round it instead:
System.out.println(Math.round(x*100)); // rounds up or down
or
System.out.println((int) (x*100));
Original:
Use String.format(String, Object...):
System.out.println(String.format("%.2f", x));
The %.2f is a format string.
Have you tried
Math.round(x)
Checkout this link for the documentation: http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)
EDIT:
I might not have fully understanded your question, but I think if you use
Math.round(Math.random*100)
You'll get a number between 0 and 100.
I prefer to use BigDecimal when dealing with floating point numbers
BigDecimal myRounded = new BigDeicmal(Math.random()).setScale(2, BigDecimal.ROUND_HALF_UP);
Since Math.random() returns a double between 0.0 to 1.0, you can just multiply the result with 100. So 0.0 * 100 = 0, 1.0 * 100 = 100, and everything in between will always be between 0 and 100.
Use Math.round() to get a full integer number. So if the random number is 0.03454, multiplied by 100 = 3.454. Round it to get 3.
correct:
int var = (int)Math.round(Math.random()*100)
INCORRECT:
int var = Math.round(Math.random()*100)
you need to downcast to integer before assign to integer variable in order to don't get an error like this:
error: incompatible types: possible lossy conversion from long to int
int var = Math.round( Math.random() * 3);
^
When you create the variable multiply it by 100 like so:
double a = Math.random()*100;
then when you have to print it put an (int) before the variable just like down here:
System.out.print((int)a);

Setting precision for double in java

DecimalFormat df = new DecimalFormat("#.000000");
int a[] = { 2, 2, 3, 3, 4, 4 };
double sum = 0.000000;
for (int i = 0; i < a.length; i++)
{
sum = sum + (double) a[i];
}
output1=Double.valueOf(df.format(sum / a.length));
where sum/a.length value is 3. output1 is double variable. Now the result I wanted is 3.000000 and it must be store in double variable output1 but I can't get it.
Although in certain cases it might work, in general there is no way to determine/force the decimal precision of a double value, or indeed any IEEE floating point number.
If you want decimal precision in Java, use BigDecimal. This is even more important if the numbers you work with represent money.
If an approximate result is good enough (and there are lots of calculations where it is), you can use double but be aware that it's a binary floating point number and accurate rounding to decimals might not always be possible.
The primitive type double is an approximation of a real number, with a sequence of (negative) powers of 2.
Hence the decimal notation 0.2 = 0*2-1 + ... + 1*2-4 + ... with an error as one would need an infinite sequence in base 2.
If one wants a precision with the value, one needs BigDecimal:
BigDecimal oneFifth = new BigDecimal("0.200"); // Precision/scale 3
BigDecimal hundredPlusOnefifth =
oneFifth.multiply(BigDecimal.valueOf(501)); // 100.200
Using a String in the constructor, BigDecimal can set the precision.
Not so nice writing expressions in BigDecimal though.
With double one might live, while carefully rounding at appropriate points in the code. There always will be a small error and, outputting needs a formatter as the number of digits is lost.
The value of 3.0 and 3.00000 are the same in a double variable. When you print it, format it the way you want:
System.out.println( df.format( output1 ) );
Looks like sum is int and you have the result of integer division (because a.length is int). Just multiply one of those values by 1.0:
output1 = Double.valueOf(df.format((sum * 1.0) / a.length));
With your edited code, your problem is not in obtaining the value of output1 but how you show it. Don't print output1 directly, instead use the DecimalFormat you used previously:
System.out.println(df.format(output1));

Categories