Conversion of a floating value without E- notation - java

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

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.

How to convert a double to a string with 2 decimal places?

I'm turning this double into a string so I can display it on a TextView. I want the string to have 2 decimal places using String.format, but I don't know where to put it in this line of text.
Example.setText(Double.toString(dValue));
Any Ideas?
The quick and dirty way is to use a formatted String and specify the number of decimal points. Lately there's been a trend of suggesting the usage of a DecimalFormat instead since it will respect different locales and the usage of commas or points as a decimal separator.
//The suggested way lately
DecimalFormat formatter = new DecimalFormat("#0.00");
twoDecimals.setText(formatter.format(2.123145));
//The usual way with some caveats
twoDecimals.setText(String.format("%.2f",2.123));
I'm pretty sure it could also be done with formatted strings, but hey.. who am I to go against the trend.
Example.setText(String.format("%.2f", dValue));
.2 means 2 decimal places
f means it's a decimal type
Try this -
DecimalFormat df = new DecimalFormat("#.00");
Example.setText(df.format(dValue));

Float value with 2 decimal places

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

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