Different Rounding Results in Java 6 and Java 8 [duplicate] - java

This question already has answers here:
Why does Math.round(0.49999999999999994) return 1?
(5 answers)
Closed 6 years ago.
I am rewriting an old Java 6 Program written to perform some scientific calculations in Java 8 and stuck up in this situation where I'm getting different results for rounding operation.
Java 6 is rounding an input like 0.499999999999999999994 to 1 but Java 8 is making it 0. I'm not able to understand the problem here.
For Instance:
private void foo() {
System.out.println(Math.round(0.499999999999999999994));
}
The above code behaves differently for different Java versions.
It would be great if someone could shed some light on this issue.

I think you stumbled on a known bug in Java 6 which was later fixed in Java 7. This explains the weird code behaviour in Java 6 and Java 8.
Bug Info:
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6430675
More information and beautiful explanation by #OliverCharlesworth can be found in this post:
Why does Math.round(0.49999999999999994) return 1
Excerpt from his post:
In Java 6 (and presumably earlier), round(x) is implemented as
floor(x+0.5). This is a specification bug, for precisely this one
pathological case. Java 7 no longer mandates this broken
implementation.

The reason why the output of your example is 0 is a different one. 0.999999999999999999994 is a double. Casting an double to an it drops the decimal places of the double value.
public class Example {
public static void main(String[] args) {
double d1 = 0.9;
Double D1 = Double.valueOf(d1);
int d1AsInt = (int)d1;
System.out.println("d1 as int:\t" + d1AsInt);
System.out.println("d1 as int:\t" + D1.intValue());
}
}
If you rely on precise values you should use BigDecimal and BigInteger.

Related

How to format print function in Java to print equal width per different number? [duplicate]

This question already has answers here:
Java output formatting for Strings
(6 answers)
Closed 11 months ago.
Given these variables:
int a = 1, b = 123, c = 55, d= 1231;
Is there a way in Java to print them with a set width of 5, say. In case number is less than five digits - only print dashes.
1----,123--,55---,1231-
I am aware that these can be achieved with some loops and if statements, looking for something similar to setw() from C++
System.out.println(String.format("%-5.5s", s).replace(" ", "-"));
In short, you can't do it directly. Java has functionality broadly similar to that of C's "printf" formatting.
You can set a field width, you can justify left or right, but your fill characters are limited to zero and space.
Documentation
If the format uses the general "%s" directive, and the corresponding argument is of a class under your control, then you can implement a 'formatTo' method to do the conversion. So a wrapper class might be useful to you.

why float and double showing different behaviour in java? [duplicate]

This question already has answers here:
What is float in Java?
(4 answers)
Closed 7 years ago.
case 1
float a=033.0 //shows compilation problem
case 2
double a=033.0 //works fine
Why case 1 is showing error but not case 2 or vice-versa?
By default java uses double type to store floating values. since you are storing double in float (down casting) java will throw an error. it can be resolved by two ways
float a=033.0f
float a= (float)033.0
case 1----float a=033.0 //shows compilation problem
case 2----double a=033.0 //works fine
In Java, decimal number is interpreted as a double ,so converting from double to float cannot be performed automatically ,so you need to give like this :
float a= 033.0f;
Its simply the understanding of Java Syntax.
You can read the Primitive data types of java.
You'll get it anywhere...
Link : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Direct to this link, do ctrl+F, & paste this "Floating-Point Literals".
You wont't waste time wandering...
For your own convenience now, you can prefer this.
float fractionNumber = 25.24F;
fractionNumber = 25.24f;
double biggerFractionNum = 56.65555D;
biggerFractionNum = 56.65555;
but generally its like this all over... later you'll get used to it.
float foo = 34.4F;
double doo = 34.4;
IMPLEMENT it right away ! ...experience it, understand it...& you'll never forget it. :)

Java regular expressions specify range of digits [duplicate]

This question already has answers here:
Using regular expressions to validate a numeric range
(11 answers)
Closed 7 years ago.
I'm trying to verify that a user inputs coordinates in the format: x,y
so I'm using regular expressions. x and y can be between 1 and 15, so I used
[1-15]\\d{1,2},[1-15]\\d{1,2}
but that didn't work because 15 isn't a digit obviously. I changed it to
\\d{1,2},\\d{1,2}
so at least I can confirm that its two one or two digit numbers, but it could be up to 99 on either side; not good. I've tried a few other ways like
\\d{1}|[1]\\d[0-5]\\d...
but nothing works and honestly I've been looking at all this so long it doesn't make sense anymore.
More importantly, is it even good practice to use java's regular expression feature? I could think of other ways to do this, but this is just for a personal project I'm working on and trying out different approaches to things I usually do messily.
I think you understand the [...] the wrong way: it means you specify a range of characters. So [1-15] means: 1to 1and 5. It is thus equivalent to 1|5.
You can however specify the digits 1 to 15 with [1-9]|1[0-5]. Plugging this into your regex results in:
([1-9]|1[0-5])\\d{1,2},([1-9]|1[0-5])\\d{1,2}

Java7 Double.toString() returns 0.005 / java6 it is 0.0050

I am upgrading from JDK6 to JDK7. The following code demonstrate shows a minor change in Double.toString()
public class StringDemo
{
public static void main(String[] args)
{
System.out.println(Double.toString(.0005));
System.out.println(Double.toString(.005)); //different string
System.out.println(Double.toString(.05));
System.out.println(Double.toString(.5));
}
}
JRE6
5.0E-4
0.0050
0.05
0.5
JRE7
I am looking for any documentation related to above change. The compatibility page does not cover it.
5.0E-4
0.005 //changed.
0.05
0.5
The output was saved in many reference files, and compared by string comparison- I need to fix the comparison, but curious to know more details about this change. Authoritative answer on why this change will get bounty.
This was a bug in Java 1.3 through 1.6 (resolved in 1.7).
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4511638
The bug report http://bugs.sun.com/view_bug.do?bug_id=4428022 contains more details. Fixed in JDK 7 (b75).
Related Reports- Quoted from the link above.
Backport: JDK-2181423 - System.out.println(0.001) outputs 0.0010
Duplicate: JDK-5078240 - Double.toString(double) adds a trailing zero
in certain cases
Duplicate: JDK-6575880 - Float.toString(float) adds trailing
zeros
Relates: JDK-6935102 - Regtest
closed/sun/misc/FloatingDecimal/ToString.java now failing.
Relates: JDK-4154042 - java.lang.FloatingDecimal could be
eliminated
The changes for OpenJDK 7 to fix this issue are available at: http://hg.openjdk.java.net/jdk7/tl/jdk/rev/f85aa3aedf41

variable/parameterized width for printf/format in Java (using * or something else?) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java printf using variable field size?
I haven't worked with Java in a while so I was looking for a way to
specify variable width in format/printf when formatting/printing output. My example shows the use with an integer, but of course I'd like this to work for other types too.
E.g., something along the lines of
int val = 8;
int wid = 5;
System.out.printf("%"*d\n", wid, val);
I could use this work-around, which is ugly:
System.out.printf("%"+wid+"d\n", val);
Was the * variable field width specifier removed from Java? This old'ish
page, section 1.3.1,
shows the use (like it would be used in C), but I can't get it to
work, resulting in:
java.util.UnknownFormatConversionException: Conversion = '*'
nor have I been able to find more recent references that this
does work.
Is there an easier way to do this other than my work-around above?
I did look around before posting and came across this about 2-year old SO question Java printf using variable field size? but is that the final word on this?
The general syntax of a format specifier is
%[parameter][flags][width][.precision][length]type
Instead of printf, you can also use
String.format("%"+wid+"d",val);
And yes, these are the only ways in case you are using a Java Formatter.

Categories