Java double initialization

Having tried a simple program (using both 0 and 100, to show the difference between “special” constants and general ones) the Sun Java 6 compiler will output the same bytecode for both 1 and 2 (cases 3 and 4 are identical to 2 as far as the compiler is concerned). So for example: double x … Read more

Why double.TryParse(“0.0000”, out doubleValue) returns false ?

it takes the localization settings at runtime into account… perhaps you are running this on a system where . is not the decimal point but , instead… In your specific case I assume you want a fixed culture regardless of the system you are running on with . as the decimal point: double.TryParse(“0.0000”, NumberStyles.Number, CultureInfo.CreateSpecificCulture … Read more

Double value to round up in Java

Note the comma in your string: “1,07”. DecimalFormat uses a locale-specific separator string, while Double.parseDouble() does not. As you happen to live in a country where the decimal separator is “,”, you can’t parse your number back. However, you can use the same DecimalFormat to parse it back: DecimalFormat df=new DecimalFormat(“0.00”); String formate = df.format(value); … Read more

Format double to 2 decimal places with leading 0s [duplicate]

OP wants leading zeroes. If that’s the case, then as per Tofubeer: DecimalFormat decim = new DecimalFormat(“0.00”); Edit: Remember, we’re talking about formatting numbers here, not the internal representation of the numbers. Double price = 32.0; DecimalFormat decim = new DecimalFormat(“0.00”); Double price2 = Double.parseDouble(decim.format(price)); System.out.println(price2); will print price2 using the default format. If you … Read more

How to set CultureInfo.InvariantCulture default?

You can set the culture of the current thread to any culture you want: Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; Note that changing the culture also affects things like string comparison and sorting, date formats and parsing of dates and numbers.

Comparing Double.NaN with itself

The reason for the difference is simple, if not obvious. If you use the equality operator ==, then you’re using the IEEE test for equality. If you’re using the Equals(object) method, then you have to maintain the contract of object.Equals(object). When you implement this method (and the corresponding GetHashCode method), you have to maintain that … Read more

Java signed zero and boxing

It is all explained in the javadoc: Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if d1.doubleValue() == d2.doubleValue() also has the value true. However, there are two exceptions: If d1 and d2 both represent Double.NaN, then the equals method … Read more