How to save and calculate Dollers in Android application [duplicate] - java

This question already has answers here:
Floating point arithmetic not producing exact results [duplicate]
(7 answers)
Closed 9 years ago.
I have to perform operation on Money(basically dollars). I have to get the price of a product then multiply with the Quantity and in a same way do the transactions.
Currently i am using the double and at some places float to perform operations on amount. They give me output like 13.789689 but i need only up to 2 digits. So that i have applied
String value = String.format(Locale.ENGLISH, "%.2f", 13.789689);
to get that upto 2 digits. But now the problem is results are not coming accurate.
Also i am to saving the Transactions information into the database and that shows variations in Cash and CC trans.
I am So frustrated by this because it's operation with money and i am loosing that. Please guide me what to best in that case.

There is nothing specific to android. In Java, it is recommended that all the monetary calculations are to be carried out by BigDecimal data type so that there will not be any rounding off issues that you would face in float and double
Here are the few links that might help you 1,2,3.

Don't use float or double for anything money related, if you need exact results (and you probably do). Try BigDecimal instead.

You can use DecimalFormat for this , i.e.
Double d=13.789689
DecimalFormat deciFor= new DecimalFormat("##.##");
String value=deciFor.format(d);
Result value will be 13.79

Related

How to get the value without round up/down in Java? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
double d0 = Double.parseDouble("53.82233040000000557");
double d1 = Double.valueOf("53.82233040000000557");
output
d0 = 53.822330400000006
d1 = 53.822330400000006
Precision Numbers in Java
Class java.math.BigDecimal is better for handling numbers where precision matters (like monetary amounts), see BigDecimal VS double.
It could be used for geo-coordinates (latitude/longitude). Although practitionars argue that double is precise enough for lat./long. - since you don't want to locate something at nano-meter scale.
Example Code
If you need high precision and scale for your number, use BigDecimal like this:
BigDecimal decimalValue = new BigDecimal("53.82233040000000557");
System.out.println("as BigDecimal: " + decimalValue.toPlainString());
// prints exactly: 53.82233040000000557
Run this code online (IDE one): Double VS BigDecimal for high precision
Read more
Read more in a tutorial on Java: BigDecimal and BigInteger
If you need precision, you have to use a BigDecimal.
The answer is that you cannot. The values you are getting are the most accurate approximation to your values that can possibly be stored in a double. There is no possible way to get a more accurate, less rounded value stored in a double.
If you require that the answers are not rounded at all, therefore, you should not be using double. The data type you should be using instead is BigDecimal.

Formatting Double to String? [duplicate]

This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 3 years ago.
String.format("%,.0f", 200000000000000000000000.0)
-> 199,999,999,999,999,980,000,000
why?
Understand the Double Data type - it is an approximation of amount and scale.
The Following assignment:
double d = 2.00000000000f;
will generate a value of 1.9999999 at times when printed. What you are seeing here is magnification of that. Double Data types also have a maximum (implementation-dependant) of how many places of significance they can support (upto 15 generally) - which is why the last 6 digits are all zeros (0)
For your particular solution, if you don't require Floating-point Data, stick to Integer.
It is because current processors(and most VMs) work like that if use default data types. Here it is explained in details
If you want precision use BigDecimal. This class is specifically intended for situations like this - to be used in currency related stuff and scientific calculations.
To format decimals in proper way Java has DecimalFormat
String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String format = decimalFormat.format(123456789.123);
System.out.println(format); // -> 123.456.789,123
Here is nice tutorial about it
Hope it helps.
My problem has been solved
String.format("%,.0f", BigDecimal( 200000000000000000000000.0, MathContext.DECIMAL64))

How to display decimal numbers in Java? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
I'm using float to display decimal numbers, but sometimes it doesn't display correct result.
For example, for 6.2/1000 the result is 0.0061999997.
I know why is this happening, but I wonder is there a way to display correct result, in this case, 0.0062?
EDIT:
How to round a number to n decimal places in Java does not answer to my question, so why did you marked my question as already been answered in other place?
Numbers I wrote are only example. In the app user can enter any number and divide / multiply number with any other number, so the result maybe won't have any decimal points, maybe it will have 4 decimals, maybe it will have 7 decimals,...
First, you need to understand that this isn't just a display issue - if you want to avoid displaying incorrect values, it helps to have the right values to start with.
You should use BigDecimal instead of float. That stores the value as an integer scaled by a factor of 10exp rather than the 2exp used by double and float.
If the BigDecimal.toString doesn't format the result the way you want, use DecimalFormat to perform the formatting instead.
Format the decimal places use this:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(decimalPlace);
String formatedValue = df.format(value);
Hope this will resolve your query.

Show only two digit after decimal [duplicate]

This question already has answers here:
how to convert double to 2 number after the dot? [duplicate]
(6 answers)
Closed 9 years ago.
How to get the double value that is only two digit after decimal point.
for example
if
i=348842.
double i2=i/60000;
tv.setText(String.valueOf(i2));
this code generating 5.81403333.
But I want only 5.81.
So what shoud I do?
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. It also supports different
kinds of numbers, including integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4), percentages (12%), and currency
amounts ($123). All of these can be localized.
Code snippet -
double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));
Output -
5.81
How about String.format("%.2f", i2)?
Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.
double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));
Many other answers only do formatting. This approach will return value instead of only print format.
double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);
I think the best and simplest solution is (KISS):
double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;
i=348842.
double i2=i/60000;
DecimalFormat dtime = new DecimalFormat("#.##");
i2= Double.valueOf(dtime.format(time));
v.setText(String.valueOf(i2));
First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.
And other aspect is providing proper result. So you want to truncate the number or round it.
So before you start you should ask your self, am i interested on the value or not.
To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

how to fix double precision issue in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java floats and doubles, how to avoid that 0.0 + 0.1 + … + 0.1 == 0.9000001?
How can I overcome the precision issue with double multiplication in java android??Please note that I am converting a string value into double value.
eg: when I multiply two double value:
double d1 = Double.valueOf("0.3").doubleValue() * Double.valueOf("3").doubleValue();
System.out.println("Result of multiplication : "+d1);
I am getting the following result : 0.8999999999999999
Some of the results that i am getting are.
0.6*3=1.7999999999999998;
0.2*0.2=0.04000000000000001;
etc.
Instead of the above results I would like to get the following results.
0.3*3=0.9;
0.6*3=1.8;
0.2*0.2=0.04;
Please remember that I am not trying to round it to the nearest integer.
You should really be using java.math.BigDecimal to avoid any precision issues, and always use a BigDecimal(String) constructor.
BigDecimal result = new BigDecimal("0.3").multiply( new BigDecimal("3.0") );
The problem isn't with multiplication. It starts with Double.valueOf("0.3"). That value can't be represented exactly in floating-point. You should use java.math.BigDecimal, and you should also Google for a page entitled "What every computer scientist should know about floating point".
Unfortunately, I am not aware of a simple way of doing exactly what you ask for.
Like Strelok says, you should not be using a floating-point type if you need exact results. However, for most purposes, it is enough to just specify a rounding precision for output. The following code is close to, but not quite, what you want:
System.out.printf("Result of multiplication : %.1g\n", d1);
For more info on the syntax of printf, see the java.util.Formatter documentation.

Categories

Resources