Display only 2 digits after decimal - java

bill[p][l][0] = new DecimalFormat("##.##").format(Double.parseDouble(i2[m][0]));
The code entered above is not working; input 10.0 gives 10 as output.

It is working - a # means the digit is only printed if it's relevant (see the documentation). Try using
bill[p][l][0] = new DecimalFormat("##.00").format(Double.parseDouble(i2[m][0]));

To format exactly up to two decimal places you should use ##.00 as ##.## will remove the trailing zeros from the value.

If you want to handle both positive and negative numbers I would recommend using BigDecimal since Double technically doesn't have any decimal values to truncate. Try something like this:
new BigDecimal(i2[m][0]).setScale(2, BigDecimal.ROUND_FLOOR)

Related

decimal points precision is lost for some munbers in case of double data type

I am suprise to see the below program please advise how it is behaving like this as i aam very much concerened with poitn to precison after decimal point , below is the progrmam
double fixedRate = 0.997500000000; //**output --->0.9975
// BigDecimal fixedRate = new BigDecimal("0.997500000000");
double fixedRate1 = 0.1234567890123456789;
System.out.println(fixedRate);
System.out.println(fixedRate1);
and the output is
0.9975
0.12345678901234568
now please advise for the first the ouput is 0.9975 but late on for next it is not truncating after decimal points but why for first then.
The precision is not lost. It is just not printed because you do not need more digits to distinguish the printed value from any other double value.
If you do want to force a certain number of fractional digits, take a look at System.out.printf() or String.format().
See https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html for more details and possible formats.
The result may look like this:
System.out.printf("%.19f%n",fixedRate);
System.out.printf("%.19f%n", fixedRate1);
This is a printing problem.Please use this format to print your values and tell me the result:
double fixedRate = 0.997500000000;
double fixedRate1 = 0.1234567890123456789;
System.out.println(String.format("%.19f", fixedRate ));
System.out.println(String.format("%.19f", fixedRate1 ));
Good Luck !
According to your question
for the first the ouput is 0.9975 but late on for next it is not
truncating after decimal points but why for first then
Since double is numeric datatype and hence cannot hold the leading and trailing zeros.
A double doesn't care about formatting - it's about storage only. When you print it, it is converted to a String (using Double's static toString method).
In simple terms the value 0.9975 is not different from 0.997500000000or it is same as 0.997500000000 as zeros after a number will not have any value.
But consider if you had value like this 0.9975000000001 then all the numbers will be printed. Check it here.
If you want to format the value then you can see this question : How to properly display a price up to two decimals (cents) including trailing zeros in Java?

Remove the last grouping separator when using DecimalFormat Grouping java

I want to format lengthy double numbers in my android calculator app
2 problems ...
First is that I want to enable Grouping by 3 so 1200 would be shown 1,200
. But for numbers like 1000 what I get is 1,
How can I get 1,000 for result ?
also another problem is that I want Results with up to 25 integer digits and 4 decimal fraction digits ... but even though I set Decimalformat maximum to 25, after number of integers surpasses 18, Digits turn to be zeros. for example what I want is
1,111,111,111,111,111,111,111,111
but I get
1,111,111,111,111,111,110,000,000,
Here's the code
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(4);
df.setMaximumIntegerDigits(25);
df.setGroupingUsed(true);
df.setGroupingSize(3);
String formatted = df.format(mResultBeforeFormatting);
what pattern should I use ?
Ok so for others who face this problem like me
for first part best pattern was
DecimalFormat df = new DecimalFormat("###,##0.####");
for second problem as "x-code" noted it apears there's no hope using double . should try using BigDecimal
I found answers to both parts of the question right here on StackOverflow.
First is that I want to enable Grouping by 3
Here are several solutions to the grouping problem.
another problem is that I want Results with up to 25 integer digits
In this case what's really happening is that Java doubles can't represent 25 decimal digits.
For this problem you might want to look at the BigDecimal class, which can represent the numbers in your example.

Java Math.pow() Rounding Error

I'm having trouble with (what I suspect is) a rounding error.
I have a string, 0.686357E-01, which I'm trying to convert to a double. I've been able to split it up using the Pattern.split() function, and I'm capturing the base and the exponent values just fine. However, once I try to multiply them appropriately, I get this as a result: 0.06863570000000001.
Here's my relevant code:
pattern = Pattern.compile("E\\+?");
String[] number = pattern.split(string);
double base = Double.parseDouble(number[0]);
int exponent = Integer.parseInt(number[1]);
number= base*Math.pow(10, exponent);
So, how do I avoid the rounding error? (There are ways that I can work around it, but if it's possible to do, then I'd like to know how to fix the issue)
Thanks.
You don't need to split it, Double.parseDouble can handle those kinds of numbers just fine.
double number = Double.parseDouble("0.686357E-01");
See? It works!
0.0686357 is not exactly representable as a double-precision value.
Two solutions:
Use e.g. BigDecimal.
Limit the displayed precision to a certain number of significant figures when converting back to human-readable.
Floating point numbers do not have perfect precision. If that is an issue, use BigDecimal:
String string = "0.686357E-01";
BigDecimal number = new BigDecimal(string);
System.out.println(number);
Double will print always like that, but the value will remain correct. You'll need to format the output to get the correct value. See DecimalFormat class.

Formatting decimal places in Java

I'm trying to format a double to just 2 decimal places in Java.
I've read the following post:
How to round a number to n decimal places in Java
For some reason, every one of those methods fails to work on certain numbers I have..
For example:
DecimalFormat df = new DecimalFormat("#.##");
normalizedValue = Double.valueOf(df.format(normalizedValue));
If I print normalizedValue I get result similar to the following:
-78.64000000000001
18.97
59.469999999999985
-63.120000000000005
(Note: some are formatted correctly... some aren't)
So, these methods seem to round, but I need something that will remove all decimals after 2 decimal places... Any suggestions?
Thank you.
The string representation given by DecimalFormat.format(...) does indeed have only 2 digits in your example. But as soon as you reconvert it into a double those accuracy issues occur. A binary base format like double will always show such effects when you try to represent "exakt" decimal fractions. You may change to BigDecimal to get rid of such effects.

How to read a double value with a certain precision

How to read a double value from a String with a certain precision (say 4) assuming the string contains something like "10.1234" using this api
If you want decimal precision, double is the wrong target type, as it is a binary format that cannot accurately represent most round decimal fractions. That double value will actually be rounded to something like 10.123399999999999999976
Instead, use BigDecimal all the way, or forget about runding while you read and manipulate the data, and round it only when you print the result.
Read The Floating-Point Guide for more information.
System.out.println(new Double(new BigDecimal("10.123456789").
setScale(4, BigDecimal.ROUND_DOWN). // choose precision and specify rounding policy
doubleValue()
));
>> run:
10.1234
I assume that your String also contains letters.
You can parse the number out of the String first:
String numberString = ...
int precision = ...
int index = numberString.indexOf(".");
numberString = numberString.substring(0, index+precision+1); // Maybe without "+1"
Double number = Double.valueOf(numberString);
You can use regular expression to truncate the String to at most 4 digits following the decimal point, then use Double.valueOf.
String[] tests = {
"12",
"12.",
"12.3",
"12.34",
"12.345",
"12.3456",
"12.34567",
"-123.45678",
"1.23456.789.0",
};
for (String test : tests) {
String truncated = test.replaceAll("(\\.\\d{4}).*", "$1");
System.out.printf("%15s %15s %15s%n",
test, truncated, Double.valueOf(truncated)
);
}
This prints:
12 12 12.0
12. 12. 12.0
12.3 12.3 12.3
12.34 12.34 12.34
12.345 12.345 12.345
12.3456 12.3456 12.3456
12.34567 12.3456 12.3456
-123.45678 -123.4567 -123.4567
1.23456.789.0 1.2345 1.2345
How the regex works
It captures a literal ., followed by up to four digits \d{4}, into \1. It also matches everything else that may follow .*, and replaces the whole thing with $1 (backreference to what \1 captured).
The advantage of this over, say, a simple indexOf approach is that it works even when there aren't 4 digits, or even when there isn't even a decimal point at all, without requiring special treatment.
See also
regular-expressions.info
Java Tutorials/Regular expressions
You can do something like
Math.round(number*100)/100
to get the precision, but this will probably not do what you want due to the internal representation of floats and doubles.
If you really need to work with a fixed number of digits after the decimal point consider using BigDecimal.
For formatting output you can use the C-like printf functionality as decribed in this article. It is not pretty but practical.

Categories

Resources