This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
I am using this JAVA program where I am multiplying a double with a double and storing it in a double.
My expected output is 7.14 as per my mathematics knowledge, but I get 7.140000000000001. I don't understand why is the 0000000000001 part is coming
public class Main
{
public static void main(String[] args) {
double a=7.0;
double b=1;
double c=a*b*1.02;
System.out.println(c);
}
}
So you are getting a super high level precision output for your operation. If you want to set a precision limit, you can do so following the example below
double no=12.786;
DecimalFormat dec = new DecimalFormat("#0.00");
System.out.println(dec.format(no));
This question already has answers here:
Why not use Double or Float to represent currency?
(16 answers)
Closed 5 years ago.
Following is my code to convert long (cents) to dollar, however, there is 1 cent difference.
My expected answer is: $123,456,789,123,456.47, but the output is $123,456,789,123,456.48
public static void main(String[] args) {
long l = 12345678912345647L;
double d = l / 100.00;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
System.out.println(formatter.format(d));
}
For numbers greater than ~70 trillion BigDecimal should be used to remain accurate.
public static void main(String[] args) {
BigDecimal l = new BigDecimal("12345678912345647");
BigDecimal d = l.divide(new BigDecimal("100.00"));
NumberFormat formatter = NumberFormat.getCurrencyInstance();
System.out.println(formatter.format(d));
}
It is rounding like that because you are getting the output of a long divided by a number to 2 decimal places and then it's being stored in the double. If you want to get the number without it being rounded up try dividing by 100.000 or by replacing the long l with double l.
This question already has answers here:
Show padding zeros using DecimalFormat
(8 answers)
Closed 7 years ago.
I have a string which has value 7. I need to convert this value in big decimal equivalent 7.000000. I tried BigDecimal(String val) and BigDecimal(BigInteger val, MathContext mc) constructors of BigDecimal but that did not work they all return 7. How can I get 7.000000?
You can use DecimalFormat to format the output. There is no way to store the unnecessary precision in the BigDecimal object though.
public static void main(String[] args) {
BigDecimal seven = new BigDecimal(7);
BigDecimal sevenWithDecimals = new BigDecimal("7.12");
DecimalFormat decF = new DecimalFormat("#.000000");
System.out.println(decF.format(seven.doubleValue()));
System.out.println(decF.format(sevenWithDecimals.doubleValue()));
}
output
7.000000
7.120000
I think you're talking about how to convert it to a String.
The constructor of BigDecimal will produce a BigDecimal representing the value you gave it, and there's no difference between a BigDecimal representing the number 7 and a BigDecimal representing the number 7.00000, any more than there's a difference between the number 7 and the number 7.00000.
When you print it out, it needs to be converted to a String, and it sounds as though at that point you want to be able to specify the number of decimal places. To do that, you want to use the DecimalFormat class:
new DecimalFormat("#0.000000").format(bigdec);
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 to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
I have read a lot of stackoverflow questions but none seems to be working for me. i am using math.round() to round off.
this is the code:
class round{
public static void main(String args[]){
double a = 123.13698;
double roundOff = Math.round(a*100)/100;
System.out.println(roundOff);
}
}
the output i get is: 123 but i want it to be 123.14. i read that adding *100/100 will help but as you can see i didn't manage to get it to work.
it is absolutely essential for both input and output to be a double.
it would be great great help if you change the line 4 of the code above and post it.
Well this one works...
double roundOff = Math.round(a * 100.0) / 100.0;
Output is
123.14
Or as #Rufein said
double roundOff = (double) Math.round(a * 100) / 100;
this will do it for you as well.
double d = 2.34568;
DecimalFormat f = new DecimalFormat("##.00");
System.out.println(f.format(d));
String roundOffTo2DecPlaces(float val)
{
return String.format("%.2f", val);
}
BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);
Go back to your code, and replace 100 by 100.00 and let me know if it works.
However, if you want to be formal, try this:
import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value);
double finalValue = (Double)df.parse(formate) ;
double roundOff = Math.round(a*100)/100;
should be
double roundOff = Math.round(a*100)/100D;
Adding 'D' to 100 makes it Double literal, thus result produced will have precision
I know this is 2 year old question but as every body faces a problem to round off the values at some point of time.I would like to share a different way which can give us rounded values to any scale by using BigDecimal class .Here we can avoid extra steps which are required to get the final value if we use DecimalFormat("0.00") or using Math.round(a * 100) / 100 .
import java.math.BigDecimal;
public class RoundingNumbers {
public static void main(String args[]){
double number = 123.13698;
int decimalsToConsider = 2;
BigDecimal bigDecimal = new BigDecimal(number);
BigDecimal roundedWithScale = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with setting scale = "+roundedWithScale);
bigDecimal = new BigDecimal(number);
BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);
}
}
This program would give us below output
Rounded value with setting scale = 123.14
Rounded value with Dividing by one = 123.14
Try :
class round{
public static void main(String args[]){
double a = 123.13698;
double roundOff = Math.round(a*100)/100;
String.format("%.3f", roundOff); //%.3f defines decimal precision you want
System.out.println(roundOff); }}
This is long one but a full proof solution, never fails
Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;
if 4.25, Output 4.25
if 4.20, Output 4.20
if 4.24, Output 4.20
if 4.26, Output 4.30
if you want to round upto 2 decimal places,then use
DecimalFormat df = new DecimalFormat("#.##");
roundToMultipleOfFive(Double.valueOf(df.format(number)));
if up to 3 places, new DecimalFormat("#.###")
if up to n places, new DecimalFormat("#.nTimes #")
public double roundToMultipleOfFive(double x)
{
x=input.nextDouble();
String str=String.valueOf(x);
int pos=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='.')
{
pos=i;
break;
}
}
int after=Integer.parseInt(str.substring(pos+1,str.length()));
int Q=after/5;
int R =after%5;
if((Q%2)==0)
{
after=after-R;
}
else
{
if(5-R==5)
{
after=after;
}
else after=after+(5-R);
}
return Double.parseDouble(str.substring(0,pos+1).concat(String.valueOf(after))));
}
seems like you are hit by integer arithmetic: in some languages (int)/(int) will always be evaluated as integer arithmetic.
in order to force floating-point arithmetic, make sure that at least one of the operands is non-integer:
double roundOff = Math.round(a*100)/100.f;
I just modified your code. It works fine in my system. See if this helps
class round{
public static void main(String args[]){
double a = 123.13698;
double roundOff = Math.round(a*100)/100.00;
System.out.println(roundOff);
}
}
public static float roundFloat(float in) {
return ((int)((in*100f)+0.5f))/100f;
}
Should be ok for most cases. You can still changes types if you want to be compliant with doubles for instance.