This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
How to Round Decimals to 2 Places after the Decimal Point (Java)
(4 answers)
Closed 7 years ago.
I'm new to java programming. I would like to round up a price to the nearest 2 decimal places with a multiple of 5.
Eg.
38.80 stays the same.
38.81 to 38.80.
38.82 to 38.80.
38.83 to 38.85.
38.84 to 38.85.
38.85 stays the same.
38.86 to 38.85.
38.87 to 38.85.
38.88 to 38.90.
38.89 to 38.90.
38.90 stays the same.
I tried the provided duplicates but they come out only to 1 decimal place.
Eg. 38.82 to 38.8.
This is my code:
import java.text.DecimalFormat;
public class RoundUp {
public static void main(String[] args){
DecimalFormat df = new DecimalFormat("#.##");
double num = 38.84;
System.out.println(df.format(Math.round(num*10.00)/10.00));
}
}
I have looked into other model answers by experts in this web but none of them really answer my question. Setting into 2 decimal places, I'm using DemicalFormat. That I know, but rounding the number, let's say 38.83 to 38.85 and 38.87 to 38.90 is what I really want.
It is a rounding system that my country is using. Can check it out here.
**
This question has been answer by #Mureinik double rounded =
Math.round(num * 100.0 / 5.0) * 5.0 / 100.0;
**
I would recommend you to use BigDecimal instead of double when you are dealing with money.
And then it would be like
BigDecimal value = new BigDecimal(38.84);
value = value.setScale(2, BigDecimal.ROUND_HALF_UP)
You can refer Javadocs for ROUND_HALF_UP and setScale
Related
This question already has answers here:
Always Round UP a Double
(8 answers)
Closed 5 years ago.
im trying to display a float number in 5 digits rounding up in the last digit, for example : 0.123455 will be displayed as 0.12346, and 0.123454 will be 0.12345.
My current code (not properly working) is as follows:
int iFactorSum = 100000;
int iRoundSum = (int) (fSumatoria * iFactorSum + 0.5);
fSumatoria = (float) iRoundSum / iFactorSum;
fSumatoria storages the number i want to convert.
Thanks
To round up, you can use Math.ceil(numberGrade).
To round to the nearest integer, use Math.round(numberGrade).
See: the Math class
From here.
Use Math.round() to round up floating point numbers
see
https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round(double)
This question already has answers here:
Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?
(14 answers)
Floating point arithmetic not producing exact results [duplicate]
(7 answers)
Closed 8 years ago.
I am having problems with the java double data type. The problem is that for some cases the result obtained is very large number of digits after the decimal point. the same calculation done on the calculator, manually hardly reached 2 digits after decimal.
the code is as follows:
public class Calculater {
public static void main(String[] args) {
// TODO Auto-generated method stub
String quantityInString="700g";
int indexOfg=quantityInString.indexOf("g");
String onlyQuantityInString=quantityInString.substring(0, indexOfg);
int onlyQuantityInInt=Integer.parseInt(onlyQuantityInString);
double perUnitCostOfThisItem=29.00;
double returnFloat=0;
returnFloat=(onlyQuantityInInt/(1000.00))*perUnitCostOfThisItem;
System.out.println("returnFloat="+returnFloat);
}
}
The program output is: returnFloat=20.299999999999997
The answer using a calculator is 20.3
I have no idea why this is happening?
I have tried it in an eclipse running on laptop and also on an Android phone
both show same result.
Try this:
float finalValue = Math.round( value * 100.0 ) / 100.0;
Try this for precise calculations. BigDecimal is more accurate than double.
String quantityInString="700g";
int indexOfg=quantityInString.indexOf("g");
String onlyQuantityInString=quantityInString.substring(0, indexOfg);
BigDecimal onlyQuantityInInt= new BigDecimal(onlyQuantityInString);
BigDecimal perUnitCostOfThisItem= new BigDecimal("29.00");
BigDecimal returnFloat= new BigDecimal(onlyQuantityInString);
returnFloat = returnFloat.divide(new BigDecimal("1000"));
returnFloat = returnFloat.multiply(perUnitCostOfThisItem);
System.out.println("returnFloat="+returnFloat);
If you need precise calculations BigDecimal should be used rather than float and double.
The output for this code is: returnFloat=20.300
If you need to know the reason why double acts like that the look at this
To format your double you can do it by
String.format("%.2f", floatValue);
Note this formats it till 2 places.
You can also use DecimalFormat. One way to use it:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Another one is to construct it using the #.## format.
This question already has answers here:
How can I truncate a double to only two decimal places in Java?
(18 answers)
Closed 8 years ago.
amount / 100 * 7 - I'am trying to get a percent from an amount, but the problem is that sometimes a get a number with to many digits after dot, how can I make it strictly return 2 digits after dot?
type is double
Use DecimalFormat API
double d = amount / 100 * 7;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
"##" denotes the 2 digit precision
You can do this
double d = Math.round(amount * 7) / 100.0;
This will give you have value which has two decimal places. (for a modest range of values i.e. < 70e12)
If you just want to print two decimal places you can use
System.out.printf("%.2f%n", d);
This question already has answers here:
Round number to only first decimal place
(3 answers)
Closed 8 years ago.
I wish I could understand how it is possible that is not rounded the decimal number obtained from the following code.
File path2 = Environment.getDataDirectory();
StatFs stat2 = new StatFs(path.getPath());
long blockSize2 = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
double result = availableBlocks * blockSize;
free = (Preference)this.findPreference("free_mem");
free.setSummary(Double.toString(result)+" GB");
In a code similar to this use this instruction and works
result = Math.round(result * 10) / 10d;
Why not work here and I still see a number with many decimal places?
If I understood your question right you need NumberFormat here:
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
nf.format(result);
This produces a number with 1 decimal places.
So if result is 6.6789 it will produce 6.7.
Related: Round number to only first decimal place
Just a note:
If you do this:
Math.round(result * 10) / 10d;
you basically say:
Multiply result with 10
Round the result
Then divide with ten.
When you got rid of the decimals at step 2. you got another bunch of decimals after the division.
This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Round a double to 2 decimal places [duplicate]
(13 answers)
Closed 9 years ago.
I am trying to Format my double value to exact 2 decimal places and it seems to working fine, here is the code i am trying
final NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
df.setRoundingMode(RoundingMode.DOWN);
df.format(value)
Till now everything is working, but i need to return double value as it is being used for other calculations and i tried
Double.parseDouble(df.format(value))
with big decimal like
BigDecimal price = new BigDecimal(df.format(number));
but it is not working as expected
like 18.50 is being converted as 18.5
Though this is not an issue with calculations but i need to show amount on the UI where i have to show exactly up to 2 decimal places.
Is there any was i can handle it in java class or i have to take care in JSP with JSTL
This is what BigDecimal is made for!
BigDecimal number = new BigDecimal(123.456);
// set 2 fraction digits
// Note that setScale() does not change the original,
// but returns a new BigDecimal.
number = number.setScale(2, RoundingMode.DOWN);
// get string representation
String text = number.toPlainString();
// get double value
double dbl = number.doubleValue();
And use BigDecimal for other calculations as well if you can.