Questions on hexadecimal-notation for primitive initialization - java

I would like to initialize a double directly by using the hexadecimal-notation. I know this works for int and Long as shown in the following example (resulting values always right):
int i = 0x10000000; // 268435456
Long li = 0x1000000000000000L; // 1152921504606846976
On the other hand, if I try do the same with doubles, it works but only in range of 4 Bytes (view comments in the code example). For the second, not valid notation the Netbeans IDE keeps telling me that is is an integer value and, thus, too large:
double d1 = 0x10000000; // 2.68435456E8
double d2 = 0x1000000000000000; // not valid
float-values work as well as they are in the range of 4 Bytes:
float f1 = 0x10000000; // 2.68435456E8
Is there a way to directly write/initialize a double with hexadecimal-notation?
Is the only reason for being able to write a Long with hex-notation that there is no "L" in this notation (in contrast to "f" for float or the not valid "." for marking doubles)?
Why is there a limitation to 4 Bytes? And why does it apply to double and not to Long?
Thank you for your advise and suggestions.

Java supports floating-point hexadecimal literals since 1.5
double d = 0x1f.1p1;

If you just want to initialize your double with an integer value in the long range, use:
double d2 = 0x1000000000000000L;
You can also supply integer hexadecimal values outside the long range using BigInteger:
double d3 = new BigInteger("123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0", 16).doubleValue();
If you need to supply hexadecimal fractions, as suggested in the previous answer, use a hexadecimal floating point literal:
double d = 0x1F.1p1;

Related

How to divide a figure and convert it to decimal but the remainder

I want to be able to divide 9245 by 1000 and get 9.245, and then push this number to my textview.
my code gives me 9.0 and not the remainder. Hope do I keep the remainder?
String playerScore1 = gameInfo.getGame_time() / 1000;
playerscore1.setText(Double.toString(playerScore1));
If getGame_time() method does not return a double/float, you need to explicitly add .0 to dividend, or cast it to double/float type.
gameInfo.getGame_time() / 1000.0;
Java by default performs integer division, which truncates the decimal part of result. To force floating point division you can also use suffix notation:
int/1000f
int/1000d
use 1000.0 then it'll convert it into Double, if you divide it by 1000 it will automatically cast it into an integer. and use data type Double for playerScore1 as it will return Double not String
Double playerScore1 = gameInfo.getGame_time() / 1000.0;
playerscore1.setText(Double.toString(playerScore1));
When using arithmetic operators, Java will always widen to the widest type used. One exception to this rules are arithmetic operations on types byte, char, and short, they are always converted to int. This is the reason why
byte b = 1;
b = b + 1;
will fail to compile due to type mismatches. But funnily enough
byte b = 1;
b += 1;
will compile and work as expected.
Back to topic: If you divide two ints, you get an int as result. If you divide an int and a float, you will get a float, ... Thus, the easiest way to make your expression behave as you want it to is to make one of the values either a float or a double.
You can denote a float literal by appending an f or F to a floating point number.
For double, you can:
just write a floating point number, they will default to double
add a ´.0´ to an integer literal to make it a double literal
append a d or D on a floating point number, to make it extra verbose that it is a double
Applying this to your code, one possible solution is:
double playerScore1 = gameInfo.getGame_time() / 1000.0;

Convert double to int without loss of precision in java

I would like to convert a double (for example price with a value of 1.90) to an integer without losses! I am making a program that processes money, and I have to input them as doubles, and then convert them to integers so that I can proccess them and for example when I have 1.90 euros and i want to convert it to cents it will appear as 189 cents instead of 190! please help me :) thanks in advance
Check the details on how doubles and floats behave in java in the JLS
Well, you could round the value to desired precision. As long as you're within given format's precision (~15 digits for double ~7 for float) you'll get good results.
double fractValue = 1.90; // 1.8999999....
int val = (int)Math.round(fractValue*100);
It's much better idea to use BigDecimal though. You will never lose any precision then.
double x = 1.89; //Or whatever
String[] y = String.valueOf(x).split("[.]"); // Returns array having 1 and 89
String z = y[0] + y[1]; //String which is = 189
if(y[1].length()==1)
z +="0"; // Add a 0 in end if required
int finalInt = Integer.parseInt(z); //Convert String to Integer
finalInt should be what you want.

Double instance variables in java

Why do double instance variables in java have a lower case d attached to them? Do they need to have this?
Example:
double area = 0d;
double avgDailyTemp = 26d;
etc...
A number literal by default is an integer. If you attempt to pass a number like ten billion into Java double it'll error since it's outside the bounds of an integer. Specifying the lowercase d explicitly defines it as a double literal instead.
double a = 10000000000; // ERROR! Integer number too large
double b = 10000000000d; // OK!
Without the d the numbers 0 and 26 are int values.
It is not the variable which requires the d, but the constant value declared. It is a "hint" to the compiler of the data type.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Why double width = 50/110000; the output is 0.000000000000000?

This is my code :
double width = 50/110000;
System.out.println("width ori is "+width );
And the output is: 0.00000000000
What's wrong ? the expected output has to be 4.5454545454545455E-4
Any body can explain to me why?
Because you're dividing two integers, so it will only take the integer part (integer division).
Dividing integers in a computer program requires special care. Some
programming languages, treat integer division (i.e by giving the integer quotient as the answer). So the answer is an integer.
Examples :
In real life In Java
4/3 = 1.33333 4/3 = 1
25/12 = 2.083333 25/12 = 2
9/2 = 4.5 9/2 = 4
50/110000 = 0.000454545 50/110000 = 0
You can cast one of the number (or both but it's actually useless) to double to avoid that :
double width = (double)50/110000;
double width = 50d/110000;
double width = 50.0/110000;
Result of int/int returns you an integer.
So the decimal part got truncated resulting you with an integer
You need to cast:
double width = (double)50/110000;
As #Josh M has pointed, You can also try :
double width = 50d / 110000d;
Explanation to what's happening:
In Java, the default type of numbers is int, so when you write 50/110000, they're both considered int, although you defined the result to be double.
When int division occurs, the result will be 0, because they are both ints, then the double will hold this value, which will be represented as double, so you're getting 0.000000.
Possible solutions:
Coding these numbers with d: 50d/110000d.
Casting one side explicitly (the other will be implicitly cast): (double)50/110000.
50.0/110000.
See Chapter 5. Conversions and Promotions, it'll really help you.

different result in java how can it be rectified

Simple calculation gives different result in java.
int a=5363/12*5;
out.println(a);// result is 2230
But actually result should be 2234.5
How can this java result be rectified?
Two issues:
The expression 5363/12*5 gives an integer result (in particular, the division is integer).
The variable a is of type int (integer).
To fix:
double a=5363.0/12*5;
out.println(a);
Note that in general you can't expect to get exact results when using floating-point arithmetic. The following is a very good read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.
5363, 12, and 5 are all being interpreted as ints. the calculation actually being performed here is:
5363/12 = 446.9… - truncated to the int value 446
446 * 5 = 2230
Try specifying a as a float, and indicate that the numbers in the calculation are also created as floats:
float a = 5363f/12f*5f
Take a as double.
Taking a as int will round it to the integer.
Because your all the literal numbers in the right hand side are integers (e.g. 5363 as opposed to 5363.0) expression is being calculated using integer arithmetic semantics i.e. / does whole number division. Thus 5262/12 equals 446 and 446*5 equals 2230. Also your variable a is an int which can only ever hold an integer value.
To fix this you need to do two things. Change the type of a to a decimal type e.g. float or double b) have at least one of 5363 and 12 represented as a decimal type e.g.
double a= 5363.0/12.0*5
Instead of using double you can re-order your expression.
Assuming 5363/12*5 = 5363*5/12 this will give you a closer answer. You have commented you want to round the result so instead you have to add half the value you are dividing by.
int a = (5363 * 5 + /* for rounding */ 6) / 12;
System.out.println(a);
prints
2235
An int is an Integer - nothing after the ..
You should be using
double a = 5363d/12*5;
It seems it has some int/double rounding issue:
double a=((double)5363/12)*5;
System.out.println("VALUE: "+a);
Prints:
VALUE: 2234.5833333333335
Edit: rounding the result to an integer value:
double a=((double)5363/12)*5;
long b=Math.round(a); //you can cast it to an int type if needed
System.out.println("ROUNDED: "+b);
Prints:
ROUNDED: 2235
Use double
double a = 5363/12*5;
System.out.println(a);
or
cast the integer, to prevent loss or precision.
int a = ((int) 5363/12*5);
System.out.println(a);

Categories