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));
}
Related
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
If the value is 200.3456, it should be formatted to 200.34.
If it is 200, then it should be 200.00.
Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.
For example:
round(200.3456, 2); // returns 200.35
Original version; watch out with this
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out.
I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.
So, use this instead
(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
Note that HALF_UP is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.
Of course, if you prefer, you can inline the above into a one-liner:
new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()
And in every case
Always remember that floating point representations using float and double are inexact.
For example, consider these expressions:
999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001
For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:
System.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));
Some excellent further reading on the topic:
Item 48: "Avoid float and double if exact answers are required" in Effective Java (2nd ed) by Joshua Bloch
What Every Programmer Should Know About Floating-Point Arithmetic
If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.
Specifically, note that round(200, 0) returns 200.0. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).
If you just want to print a double with two digits after the decimal point, use something like this:
double value = 200.3456;
System.out.printf("Value: %.2f", value);
If you want to have the result in a String instead of being printed to the console, use String.format() with the same arguments:
String result = String.format("%.2f", value);
Or use class DecimalFormat:
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
I think this is easier:
double time = 200.3456;
DecimalFormat df = new DecimalFormat("#.##");
time = Double.valueOf(df.format(time));
System.out.println(time); // 200.35
Note that this will actually do the rounding for you, not just formatting.
The easiest way, would be to do a trick like this;
double val = ....;
val = val*100;
val = Math.round(val);
val = val /100;
if val starts at 200.3456 then it goes to 20034.56 then it gets rounded to 20035 then we divide it to get 200.34.
if you wanted to always round down we could always truncate by casting to an int:
double val = ....;
val = val*100;
val = (double)((int) val);
val = val /100;
This technique will work for most cases because for very large doubles (positive or negative) it may overflow. but if you know that your values will be in an appropriate range then this should work for you.
Please use Apache commons math:
Precision.round(10.4567, 2)
function Double round2(Double val) {
return new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue();
}
Note the toString()!!!!
This is because BigDecimal converts the exact binary form of the double!!!
These are the various suggested methods and their fail cases.
// Always Good!
new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue()
Double val = 260.775d; //EXPECTED 260.78
260.77 - WRONG - new BigDecimal(val).setScale(2,RoundingMode.HALF_UP).doubleValue()
Double val = 260.775d; //EXPECTED 260.78
260.77 - TRY AGAIN - Math.round(val * 100.d) / 100.0d
Double val = 256.025d; //EXPECTED 256.03d
256.02 - OOPS - new DecimalFormat("0.00").format(val)
// By default use half even, works if you change mode to half_up
Double val = 256.025d; //EXPECTED 256.03d
256.02 - FAIL - (int)(val * 100 + 0.5) / 100.0;
double value= 200.3456;
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(value));
If you really want the same double, but rounded in the way you want you can use BigDecimal, for example
new BigDecimal(myValue).setScale(2, RoundingMode.HALF_UP).doubleValue();
double d = 28786.079999999998;
String str = String.format("%1.2f", d);
d = Double.valueOf(str);
For two rounding digits. Very simple and you are basically updating the variable instead of just display purposes which DecimalFormat does.
x = Math.floor(x * 100) / 100;
Rounding a double is usually not what one wants. Instead, use String.format() to represent it in the desired format.
In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?
You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.
200.3456 * 100 = 20034.56;
(int) 20034.56 = 20034;
20034/100.0 = 200.34;
You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.
value = (int)(value * 100 + 0.5) / 100.0;
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);
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);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Round a double to 2 significant figures after decimal point
i've got lat and long point like this,
x1: 11.955165229802363
y1: 79.8232913017273
i need to convert 4 decimal point
x1 = 11.9552
y1 = 79.8233
Try
double roundTwoDecimals(double d)
{
DecimalFormat twoDForm = new DecimalFormat("#.####");
return Double.valueOf(twoDForm.format(d));
}
Math.ceil(x1* 10000) / 10000
Replace 10000 with 10^N, where N is number of digits after dot. In case of 4 digits after dot, precision shouldn't be lost.
Try this
String.format("%.4f", 11.955165229802363)
Assuming you want to round/truncate the decimal, and speed is not a large consideration, you want to use BigDecimal(BigInteger unscaledVal, int scale) with scale set to 4.
DecimalFormat dtime = new DecimalFormat("#.####");
^^^^
x1= Double.valueOf(dtime.format(x1));
float round = Round(num,4);
System.out.println("Rounded data: " + round);
}
public float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
If you only want to display the value like that, use a DecimalFormat to convert the value to a string, then display that.
If you really want to round it to four digits, you can achieve that by multiplying by 10000, rounding, then dividing again. However, I would advise against it, since not all decimal numbers can be properly represented in floating point format. Changes are you'll just get something like you already had.
If you really want four digits to work with as an internal state, use a BigDecimal instead. It is properly equipped to do what you want.
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
If the value is 200.3456, it should be formatted to 200.34.
If it is 200, then it should be 200.00.
Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.
For example:
round(200.3456, 2); // returns 200.35
Original version; watch out with this
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
This breaks down badly in corner cases with either a very high number of decimal places (e.g. round(1000.0d, 17)) or large integer part (e.g. round(90080070060.1d, 9)). Thanks to Sloin for pointing this out.
I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.
So, use this instead
(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
Note that HALF_UP is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.
Of course, if you prefer, you can inline the above into a one-liner:
new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()
And in every case
Always remember that floating point representations using float and double are inexact.
For example, consider these expressions:
999199.1231231235 == 999199.1231231236 // true
1.03 - 0.41 // 0.6200000000000001
For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:
System.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));
System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));
Some excellent further reading on the topic:
Item 48: "Avoid float and double if exact answers are required" in Effective Java (2nd ed) by Joshua Bloch
What Every Programmer Should Know About Floating-Point Arithmetic
If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.
Specifically, note that round(200, 0) returns 200.0. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).
If you just want to print a double with two digits after the decimal point, use something like this:
double value = 200.3456;
System.out.printf("Value: %.2f", value);
If you want to have the result in a String instead of being printed to the console, use String.format() with the same arguments:
String result = String.format("%.2f", value);
Or use class DecimalFormat:
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
I think this is easier:
double time = 200.3456;
DecimalFormat df = new DecimalFormat("#.##");
time = Double.valueOf(df.format(time));
System.out.println(time); // 200.35
Note that this will actually do the rounding for you, not just formatting.
The easiest way, would be to do a trick like this;
double val = ....;
val = val*100;
val = Math.round(val);
val = val /100;
if val starts at 200.3456 then it goes to 20034.56 then it gets rounded to 20035 then we divide it to get 200.34.
if you wanted to always round down we could always truncate by casting to an int:
double val = ....;
val = val*100;
val = (double)((int) val);
val = val /100;
This technique will work for most cases because for very large doubles (positive or negative) it may overflow. but if you know that your values will be in an appropriate range then this should work for you.
Please use Apache commons math:
Precision.round(10.4567, 2)
function Double round2(Double val) {
return new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue();
}
Note the toString()!!!!
This is because BigDecimal converts the exact binary form of the double!!!
These are the various suggested methods and their fail cases.
// Always Good!
new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue()
Double val = 260.775d; //EXPECTED 260.78
260.77 - WRONG - new BigDecimal(val).setScale(2,RoundingMode.HALF_UP).doubleValue()
Double val = 260.775d; //EXPECTED 260.78
260.77 - TRY AGAIN - Math.round(val * 100.d) / 100.0d
Double val = 256.025d; //EXPECTED 256.03d
256.02 - OOPS - new DecimalFormat("0.00").format(val)
// By default use half even, works if you change mode to half_up
Double val = 256.025d; //EXPECTED 256.03d
256.02 - FAIL - (int)(val * 100 + 0.5) / 100.0;
double value= 200.3456;
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(value));
If you really want the same double, but rounded in the way you want you can use BigDecimal, for example
new BigDecimal(myValue).setScale(2, RoundingMode.HALF_UP).doubleValue();
double d = 28786.079999999998;
String str = String.format("%1.2f", d);
d = Double.valueOf(str);
For two rounding digits. Very simple and you are basically updating the variable instead of just display purposes which DecimalFormat does.
x = Math.floor(x * 100) / 100;
Rounding a double is usually not what one wants. Instead, use String.format() to represent it in the desired format.
In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?
You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.
200.3456 * 100 = 20034.56;
(int) 20034.56 = 20034;
20034/100.0 = 200.34;
You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.
value = (int)(value * 100 + 0.5) / 100.0;