Float value with 2 decimal places - java

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

Related

Java DecimalFormat rounding down

I am using DecimalFormatter to read in formatted decimal string values and convert them to float. However, when I run:
DecimalFormat formatter = new DecimalFormat("####,####.00");
String floatStr = "177,687.71";
float val1 = formatter.parse(floatStr).floatValue();
System.out.println(val1);
...I get 177678.7 instead of 177678.71. Why is this? How do I avoid rounding the hundredths place?
Thanks!
You appear to need more precision than a float to represent that number.
Taking the formatter out of the picture:
Float.parseFloat("177687.71");
177687.7 // Ouch
Double.parseDouble("177687.71");
177687.71 // Ok
It seems that you'll need to use a double instead.
If this is for representing money though as #Dawood is suggesting , then yes, do not use floating types to represent money, since they are estimations and will accumulate errors over time. A format like BigDecimal would be more appropriate, or even just storing an integer representing cents. Money is not something that you want to subject to rounding errors.

Set n decimal places in BigDecimal and format the number Java

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

Conversion of a floating value without E- notation

I have different float values like
0.0000009
8145.32
123.00001
1235.01000
I want them showing to a TextView or converting them to string without getting an exponential notation.
when I use String.format("%.8f", num), It is getting random values after the real number ( num = 8145.32 -> 8145.32539487).
Help me, Thank you
Try this use DecimalFormat
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits
SAMPLE CODE
Double value = 123456434.678;
DecimalFormat decimalFormat = new DecimalFormat("#0.00");
Log.e("MY_VALUES", decimalFormat.format(value));
OUTPUT
com.example.nilesh.testapp E/MY_VALUES: 123456434.68

I need to round a float to two decimal places in Java [duplicate]

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.

How can I convert a double to a string without notation and with a high amount of accuracy in Java?

I'm trying to convert a double to a string without notation, and tried this:
f= Double.valueOf(c.getString(c.getColumnIndex(NotesDbAdapter.KEY_VALUE)));
NumberFormat formatter = new DecimalFormat("###.##############");
However, the value of 7^3^7 is returning as: 558546000000000000 opposed to 558545864083284007. As always help would be greatly appreciated.
You already had the value as a String. Why convert it to double at all?
You can't get precision out of a double that it cannot hold. 558545864083284007 has 18 decimal digits. A double has 53 bits of binary precision, which is about 15.9 decimal digits. Google for 'What every computer scientist should know about floating-point'.
###.############## is not a suitable formatting mask for 558545864083284007.
If you already have the huge decimal number in string format, try using the BigDecimal class, something like this:
BigDecimal bigDecimalValue = new BigDecimal("1234567890123456789012345678901234567890.54321");
LOGGER.info("bigDecimalValue: {}", bigDecimalValue.toPlainString());
You should get back the original value with no precision loss:
bigDecimalValue: 1234567890123456789012345678901234567890.54321

Categories