How to display decimal numbers in Java? [duplicate] - java

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.

Related

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 save and calculate Dollers in Android application [duplicate]

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

Formatting floating numbers to certain length [duplicate]

This question already has answers here:
How to nicely format floating numbers to string without unnecessary decimal 0's
(29 answers)
Closed 9 years ago.
I want to limit my numbers to 7 significant figures (I believe this is known as significant digits in American English) with a maximum of 5 decimal places but I am ensure on how to do this.
I am currently using %-7.5f but this always prints 5 decimal places, even if those places aren't significant.
I.e. 3.75 becomes 3.75000
Here's some examples to try and further clarify what I am after:
3097.0 -> 3097
10.39596 -> 10.396
79.6103426 -> 79.61034
I.e. No leading or trailing 0s, 7 significant figures and at most 5 decimal places.
I'm trying to do this as I am working on upgrading an old program written in QBasic and this is how it formats it's floating point numbers when they are displayed. I want my Java code to output the numbers this way simply to make it easier to compare the results.
You can use DecimalFormat for this
double value1 = 10.39596;
double value2 = 79.6103426;
DecimalFormat df = new DecimalFormat("#.#####");
System.out.print(df.format(value1));
System.out.print(df.format(value2));
I suggest to use DecimalFormat for this purpose
new DecimalFormat("#.#####").format(d)
this pattern limits fractional part to max 5 digits
What about
DecimalFormat format = new DecimalFormat("#.#####");
System.out.println(format.format(79.6103426));

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.

Getting numbers after decimal Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange floating-point behaviour in a Java program
Why does JSP/JSTL division by 1000 sometimes give remainder?
I am trying to get the numbers after the decimal.
ex: 60.4 -> 0.4
Yet, when do
double a = 60.4 % 1;
it comes out to be 0.3999999999999986.
Why is this? And how could it be fixed?
Use fixed-point types
BigDecimal src = new BigDecimal("60.4");
BigDecimal a = src.remainder(BigDecimal.ONE);
You can use DecimalFormat to do your desired task.
OK here is how you can do: How to get the numbers after the decimal point? (java)
I think this is exactly what you are looking for. So essentially you can use:
double x = d - Math.floor(d);
OR
BigDecimal class for exact digits after decimal.

Categories

Resources