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);
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
My problem while I am converting Double to BigDecimal I am loosing original value.
My requirement like input would be like Double val = 10435383974769502920d and want to convert like 10435.383974769502920 but getting below output.
I have tried with Double BigDecimal..but no success
Double val = 10435383974769502920d;
System.out.println(BigDecimal.valueOf(val).movePointLeft(15));
output : 10435.383974769502
Double val = 10435383974769502920d;
A double simply can't hold that many digits. Doubles are limited to ~15 decimal digits of precision. It's not BigDecimal that's losing the extra digits; it's the double you're starting with.
>>> System.out.printf("%f\n", 10435383974769502920d);
10435383974769502000.000000
Construct the BigDecimal with a string to avoid losing precision.
String val = "10435383974769502920";
System.out.println(new BigDecimal(val).movePointLeft(15));
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)
What's the best practice to round a float to 2 decimals? [duplicate]
(7 answers)
Closed 9 years ago.
I've got a float value and i need to have only two decimals after comma. I'm using this code:
public static float getWhatINeed() {
StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
float total =
((float)statFs.getBlockCount() * statFs.getBlockSize()) / (1073741824);
return total;
}
And it returns for example: 12.552425 in a textview. I need display something like: 12.55 that is enough for me. I saw this:
String s = String.format("%.2f", 1.2975118);
somewhere but I can't use it in my case because I use a float value and I need to use float. How could I solve this?
There is no mechanism to limit the number of decimal points in a float. A float is a float and it has an "unlimited" number of decimals. The String display of a float may be limited to a format only showing a specific number of decimals.
If you really NEED 2 decimals, use BigDecimal
You basically have 4 options:
return a float and deal with the fact that there are n decimal places
format to a String (which means a lot of string parsing if you need to do calculation)
convert to use BigDecimal
convert to use int and assume that the ones digit represents hundredths.
Did you try:
new DecimalFormat("00.00").format(1.2975118);
You can try as follows
DecimalFormat df = new DecimalFormat("0.##");
float a=1.256f;
System.out.println(df.format(a));
}
Out put
1.26
After setting precision and get as a String You can canvert it back to float by
float f = Float.parseFloat(YourString);
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.
This question already has answers here:
Are there any functions for truncating a double in java?
(11 answers)
Closed 9 years ago.
I want to truncate the double.
e.g.
double d=3.123456789087654;
if I want to truncate It to the 10th digit after the decimal
the result should be
result: 3.1234567890
I don't need round off value as a result
I tried my own function as
static double truncateDouble(double number, int numDigits) {
double result = number;
String arg = "" + number;
int idx = arg.indexOf('.');
if (idx!=-1) {
if (arg.length() > idx+numDigits) {
arg = arg.substring(0,idx+numDigits+1);
result = Double.parseDouble(arg);
}
}
return result ;
}
but didn't get the appropriate result as I want..
can anybody please help me to clear my problem.
Does java supports such any function that supports truncation not round off??
In general, you can't, at least not by using double. The reason is that many numbers simply can't be represented exactly, even if they have a small number of decimal digits.
Take 0.1 as an example. The nearest double is 0.1000000000000000055511151... and no amount of truncation would give you exactly 0.1.
You can use the DecimalFormat class.
double d = 3.123456789087654;
DecimalFormat newFormat = new DecimalFormat("#.##########");
double tenDecimal = Double.valueOf(newFormat.format(d));
this will round the last digit.
I am agree with NPE. no amount of truncation would give you exactly 0.1.
only way is to convert in to string and after substring convert back to double.