I am currently using the BigDecimal and with variable number of digits after decimal point. I need to be able to format the number with loosing the number of digits which I had set, because when I use format then it reduces the decimal digits to 2 - 4.
str1 =bigDecimal.setScale(numberOfDecimalPlaces, RoundingMode.HALF_UP);
str2 = NumberFormat.getInstance().format(bigDecimal.setScale(numberOfDecimalPlaces, RoundingMode.HALF_UP));
The first list works fine but when I want to format the String/BigDecimal then it drops the decimal places.
Note: Decimal place will vary from 0 to 15(from user). I am using Android Studio-API15/Java. Precision is important in my app, formatting is to improve readability.
As mentioned by #JB Nizet, you need to tune NumberFormat acc. to your need.
Below is a working example:
int numberOfDecimalPlaces = 6;
BigDecimal bigDecimal = new BigDecimal(11212.122323);
bigDecimal.setScale(numberOfDecimalPlaces, RoundingMode.HALF_UP);
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMinimumFractionDigits(numberOfDecimalPlaces);
System.out.println(numberFormat.format(bigDecimal));
Output:
11,212.122323
Related
So I use ...
System.out.printf("%.2f",variable);
and it works. But if the second decimal place is a 0, it just ignores the zero and gives the answer to one decimal place. How can I get two decimal places including the zero?
Thanks.
you can use DecimalFormat like this
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
String format = decimalFormat.format(variable);
I want to round any double to a double with the format of one decimal point and one decimal place so 29575.347434 would be 2.3.
Tried doing this with decimalFormat but when i try #.# i just get a string in the format of 29575.3 with a , and i have no idea idea how to cut off all decimal points while keeping my value a double.
You could get the number as String, take the first digit and the digit after '.'. For non-negative numbers that would be
String s = Double.toString(29575.347434);
double d = Double.parseDouble(s.charAt(0) + "." + s.charAt(s.indexOf('.') + 1));
System.out.println(d); // 2.3
If the number can be negative, you would have to correct the code for the possible minus sign.
You could accomplish this by using the modulo operator %.
It looks like your decimal formatting is working with #.#. That will give you the whole number and one decimal place. You can then do your number 29575.3 % 10 and get 5.3.
Try this code and see:
System.out.println(29575.3d % 10);
Try the following:
Number(parseFloat(29575.347434).toFixed(1))
You could also pass a string , because parseFloat() would convert it to number, then trunkate to wished decimal (output is string again), then convert back to decimal by function Number().
Works for me.
In Android, the value entered into the EditText is converted to float using the following line of code.
Float addPurchUnitCostPrice = Float.valueOf(addPurchaseCostPrice.getText().toString());
I would like to have the value of addPurchUnitCostPrice with 2 decimal places (always). How can this be done?
Floating-point values don't have decimal places. They have binary places, and the two are incommensurable. If you want decimal places you have to use a decimal radix, i.e. BigDecimal.
You will be better off using the currency formatter in Android, however it requires a double. The currency formatter will also deal with countries that use commas in place of decimal points.
So change your code to
double addPurchUnitCostPrice = Double.parseDouble(addPurchaseCostPrice.getText().toString());
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
String formattedPrice = currencyFormat.format(price);
You will create price with 2 decimal places and format according to the country defined by the users device.
You can just use BigDecimal for that
Why I get trailing so many numbers when I run below code?
BigDecimal lat = new BigDecimal(0.0077);
System.out.println(lat);
output >>
0.00770000000000000024702462297909733024425804615020751953125
I want to print exactly what I entered. How can I do this?
Most finite decimal fractions cannot be exactly represented by floating-point, so that is the approximation you get when you create the floating-point literal 0.0077.
To avoid the problem, use the constructor BigDecimal(String val) instead:
BigDecimal lat = new BigDecimal("0.0077");
As #TimB points out, if you already have a double value, you can also use:
BigDecimal lat = BigDecimal.valueOf(doubleVal);
Also, here is the mandatory reference to What Every Computer Scientist Should Know About Floating-Point Arithmetic.
When you have a number like 0.077 this cannot be exactly represented and in fact you get a number which is almost this, but with a small error. When you print this number as a string, the code to do this "knows" to discard the small error and you see the number you expect.
BigDecimal tries to give you a faithful representation and it is doing what it should even if this is surprising. What you want to use is the following method
BigDecimal bd = BigDecimal.valueOf(0.077);
In this case the BigDecimal takes the value as it would be printed, instead of the true value represented.
why is it so long?
To accurately represent a 53-bit fraction (double has a 53-bit mantissa) you need 53 decimal digits. e.g. every time you multiple by 10 to get another digit, you multiple 2 (and 5) which makes the lower bit 0 and eventually you guarentee to have all 0 bits and no more digits.
Try this:
System.out.println(String.format("%.4f",lat));
where 4 in %.4f specified how many decimal places you want to display
Note that this will only format your output display. the actual value of lat however still 0.00770000000000000024702462297909733024425804615020751953125
You can also use NumberFormat and specify the fraction digits setMinimumFractionDigits(4)
BigDecimal lat = new BigDecimal(0.0077);
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(4);
System.out.println(nf.format(lat));
BigDecimal lat = new BigDecimal(0.0077);
lat=lat.setScale(4,RoundingMode.HALF_EVEN);
System.out.println(lat);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to round a number to n decimal places in Java
I am having difficulties rounding a float to two decimal places. I have tried a few methods I have seen on here including simply just using Math.round(), but no matter what I do I keep getting unusual numbers.
I have a list of floats that I am processing, the first in the list is displayed as 1.2975118E7. What is the E7?
When I use Math.round(f) (f is the float), I get the exact same number.
I know I am doing something wrong, I just am not sure what.
I just want the numbers to be in the format x.xx. The first number should be 1.30, etc.
1.2975118E7 is scientific notation.
1.2975118E7 = 1.2975118 * 10^7 = 12975118
Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.
You could use String.format.
String s = String.format("%.2f", 1.2975118);
// 1.30
If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat class. It's very simple:
double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);
Which will output (depending on locale):
$2.30
Also, if currency isn't required (just the exact two decimal places) you can use this instead:
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);
Which will output 2.30
You can make use of DecimalFormat to give you the style you wish.
DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number)); // prints 1.30E7
Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.
Try looking at the BigDecimal Class. It is the go to class for currency and support accurate rounding.