I jsut found this code snippet and was wondering what the 50d actually means? I've been searching the web, but can't find anything useful.
Here' the complete code snippet:
public int CalculateMinimumDiameterFilter(){
CalculateFilterAreaRequirement();
double val1 = filterAreaRequirement /Math.PI;
double val2 = Math.sqrt(val1);
double val3 = val2 * 2;
int val4 = (int)Math.round(val3 * 1000);
minimumDiameterFilter = (int) (Math.ceil(val4 / 50d) * 50);
return minimumDiameterFilter;
}
Can anyone explain to me what the 50d actually does?
It is an explicit declaration of a number to be a double as defined in the JLS
3.10.2. Floating-Point Literals
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d
You may take a look at Java Primitive Data Types which will give you a good explanation.
50d in this case means the 50 is not of type integer (int) by of type double (50.0).
Not only we can do 50d. You may also see people writing things like:
long serialNo = 1234567L;
In this case the L after the number means that I want to let serialNo be of type long. If you don't place the L, the default type of whole number will be integer (int).
Instead of writing 50d, the person who writes that code could have written it as 50.0 as well. It will mean the same thing in this case because by default, floating point values in Java are double. Whole numbers are int unless otherwise specified by the postfix (such as l, d, f..etc).
Example:
double d1 = 50.0; //ok! 50.0 will be double by default
double d2 = 50.0d; //ok! 50.0 is already in double, no harm putting a "d"
double d3 = 50d; //ok! 50 becomes a double
double d4 = 50; //ok! trying to store int into double (no loss of precision)
double d5 = 50f; //ok! trying to store float into double (no loss of precision)
float f1 = 0.1f; //ok!
float f2 = 0.0; //not ok! trying to store double into float (loss of precision)
float f3 = 50d; //not ok! trying to store double into float (loss of precision)
50d means the number 50 with double type.
This is required because val4 as an int, divided by 50 as an int, will return an int and Java will be rounding it to the floor, which is not what is expected.
d is short for double. Standard the number 50 without any decimal (ie: 50.0) is just an int. You need to add the d to plain 50 to state that you want it expressed as a double.
The d suffix forces it to be a double literal instead of an int literal.
Related
My question is two-part.
Why does the following work fine in Eclipse? Isn't "Double" a class?
Double h = 2.5;
double j = 2;
Why does "Double" above give me an error when I don't assign a decimal value to it, but "double" is fine whether or not I assign a decimal value to it?
As was already mentioned, the term is autoboxing. The object wrappers for the primitive types will automatically convert.
As to your second part,
Double a = 2;
Doesn't work since 2 is not a double and the auto boxing only works between the same types. In this case 2 is an int.
But if you cast it.
Double a = (double)2;
works just fine.
double a = 2;
works because an int can be automatically converted to a double. But going the
other way doesn't work.
int a = 2.2; // not permitted.
Check out the Section on conversions. In the Java Language Specification. Warning that it can sometimes be difficult to read.
Amended Answer.
In java you can cast up or down or have narrowing or widening casts (going from a 32 bit to 16 bit) value is narrowing. But I tend to think about it is losing vs not losing something. In most cases if you have the potential to lose part of value in assignment, you need to cast, otherwise you don't (See exceptions at end). Here are some examples.
long a = 2; // 2 is an integer but going to a long doesn't `lose` precision.
int b = 2L; // here, 2 is a long and the assignment is not permitted. Even
// though a long 2 will fit inside an int, the cast is still
// required.
int b = (int)2L; // Fine, but clearly a contrived case
Same for floating point.
float a = 2.2f; // fine
double b = a; // no problem, not precision lost
float c = b; // can't do it, as it requires a cast.
double c = 2.2f; // a float to a double, again a not problem.
float d = 2.2; // 2.2 is a double by default so requires a cast or the float designator.
float d = (float)2.2;
Exceptions
No cast is required when converting from int to float or long to double. However, precision can still be lost since the floats only have 24 bits of precision and doubles only have 53 bits of precision.
To see this for ints you can run the following:
for (int i = Integer.MAX_VALUE; i > Integer.MAX_VALUE-100; i--) {
float s = i;
int t = (int)s; // normal cast required
if (i != t) {
System.out.println (i + " " + t);
}
}
Double is a wrapper class, creating a new Double casts a primitive variable of the SAME type into a Object. For Double h = 2, you are wrapping a int into a Double. Since wrapping only works between same types, if you want your Double variable be 2, then you should use
Double h = 2.0;
I am facing an issue related to converting double to float. Actually, I store a float type, 23423424666767, in a database, but when we get data from the database in the below code, getInfoValueNumeric(), it's of double type. The value we get is in the 2.3423424666767E13 form.
So how do we get a float format data like 23423424666767?
2.3423424666767E13 to 23423424666767
public void setInfoValueNumeric(java.lang.Double value) {
setValue(4, value);
}
#javax.persistence.Column(name = "InfoValueNumeric", precision = 53)
public java.lang.Double getInfoValueNumeric() {
return (java.lang.Double) getValue(4);
}
Just cast your double to a float.
double d = getInfoValueNumeric();
float f = (float)d;
Also notice that the primitive types can NOT store an infinite set of numbers:
float range: from 1.40129846432481707e-45 to 3.40282346638528860e+38
double range: from 1.7e–308 to 1.7e+308
I suggest you to retrieve the value stored into the Database as BigDecimal type:
BigDecimal number = new BigDecimal("2.3423424666767E13");
int myInt = number.intValue();
double myDouble = number.doubleValue();
// your purpose
float myFloat = number.floatValue();
BigDecimal provide you a lot of functionalities.
Convert Double to Float
public static Float convertToFloat(Double doubleValue) {
return doubleValue == null ? null : doubleValue.floatValue();
}
Convert double to Float
public static Float convertToFloat(double doubleValue) {
return (float) doubleValue;
}
This is a nice way to do it:
Double d = 0.5;
float f = d.floatValue();
if you have d as a primitive type just add one line:
double d = 0.5;
Double D = Double.valueOf(d);
float f = D.floatValue();
Converting from double to float will be a narrowing conversion. From the doc:
A narrowing primitive conversion may lose information about the
overall magnitude of a numeric value and may also lose precision and
range.
A narrowing primitive conversion from double to float is governed by
the IEEE 754 rounding rules (§4.2.4). This conversion can lose
precision, but also lose range, resulting in a float zero from a
nonzero double and a float infinity from a finite double. A double NaN
is converted to a float NaN and a double infinity is converted to the
same-signed float infinity.
So it is not a good idea. If you still want it you can do it like:
double d = 3.0;
float f = (float) d;
To answer your query on "How to convert 2.3423424666767E13 to
23423424666767"
You can use a decimal formatter for formatting decimal numbers.
double d = 2.3423424666767E13;
DecimalFormat decimalFormat = new DecimalFormat("#");
System.out.println(decimalFormat.format(d));
Output : 23423424666767
The problem is, your value cannot be stored accurately in single precision floating point type. Proof:
public class test{
public static void main(String[] args){
Float a = Float.valueOf("23423424666767");
System.out.printf("%f\n", a); //23423424135168,000000
System.out.println(a); //2.34234241E13
}
}
Another thing is: you don't get "2.3423424666767E13", it's just the visual representation of the number stored in memory. "How you print out" and "what is in memory" are two distinct things. Example above shows you how to print the number as float, which avoids scientific notation you were getting.
First of all, the fact that the value in the database is a float does not mean that it also fits in a Java float. Float is short for floating point, and floating point types of various precisions exist. Java types float and double are both floating point types of different precision. In a database both are called FLOAT. Since double has a higher precision than float, it probably is a better idea not to cast your value to a float, because you might lose precision.
You might also use BigDecimal, which represent an arbitrary-precision number.
Use dataType casting. For example:
// converting from double to float:
double someValue;
// cast someValue to float!
float newValue = (float)someValue;
Cheers!
Note:
Integers are whole numbers, e.g. 10, 400, or -5.
Floating point numbers (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
Doubles are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).
Float.parseFloat(String.valueOf(your_number)
All integer literals are treated as int in java and floating point literals are treated as double in java.
Then why does
byte b =10;
does not give any error but
float f = 10.0;
gives a loss of precision error when in both cases down-casting takes place?
In the case of int to byte, there's no real concern about a loss of precision, because both types have the same degree of granularity. You'll get an error if you try to convert a literal with a value outside the range of byte to byte. (The error message given in that case is slightly misleading.)
In the case of double to float, you can have a constant value which is in the right range, but still lose precision. In your specific case of 10.0, the value can be represented exactly in both float and double, but that's not the case in general.
As an example of that, consider this:
float f = (float) 10.1; // Or float f = 10.1f;
double d = 10.1;
System.out.println(f == d); // Prints false
That's because precision is being lost in the conversion from double tofloat - neither type can represent 10.1 exactly, but double gets close to it than float does. The == operator will mean f is converted back to a double, with a different value to d.
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 9 years ago.
When I run,
public static void main(String[] args)
{
float num = 145/156;
System.out.println(num);
}
I get output 0.0, but expected output is 0.92948717.
Any help is appreciated.
Division of an integer to an integer results an integer.
So you are getting 0 because the data is getting truncated.
You need to type cast this to float
float num = (float)145/156;
145/156 is 0.something, but because default numbers are coded as int in Java, you'll loose what's after 0 because the result will be truncated.
You should cast one of the sides (The other will be implicitly cast).
use
public static void main(String[] args)
{
float num = (float)145/156;
System.out.println(num);
}
As, 145/156 is int/int, so result is 0, type casted to float i.e 0.0
145 and 146 literals are integer and / is integer division.
try to use just 145f (the f denote float) to force the decimal division.
Why has no-one mentioned the shorter alternative?
float num = 145f/156;
cast 145/156 to float like this float num = (float)145/156;
You just need to cast at least one of the operands to a float
float num = (float) 145 / 156;
or
float num = 145 / (float) 156;
here what you are doing is like,
int a = 145;
int b = 156;
float num = a/b;
that's why you get point zero at the end.
So to get the expected output you must first cast it as follows
float num = (float) a/b;
145 and 156 are both of type int, thus the result is 'interpreted' as an integer (everything behind the dot is truncated, so 0.92948717 will become 0), and saved into a variable of type float, which is presented as 0.0.
Cast at least one of both numbers to a float in order to signal the machine to handle the result as a float.
float num = (float) 145 / 156;
Alternatively, you can suffix the number with an f to signal the machine to 'interpret' the number as a float:
float num = 145f / 156;
The numbers you have used are integers. Integer division in Java results in an integer. Apart from casting the first number to float to force a conversion and proper floating-point operation, like this:
float num = (float)145/156;
you can also write the expression like this:
float num = 145f/156;
This way, by adding f at the end, the number 145f is interpreted as float.
145 and 156 are both ints, make sure at least one has decimals. Example:
float num = (145.0 / 156);
I've seen some of this symbols, but I cannot find anything strange with it,
double d = 5D;
float f = 3.0F;
What does the D and F behind 5 exactly means?
Means that these numbers are doubles and floats, respectively. Assume you have
void foo(int x);
void foo(float x);
void foo(double x);
and then you call
foo(5)
the compiler might be stumped. That's why you can say 5, 5f, or 5.0 to specify the type.
D stands for double
F for float
you can read up on the basic primitive types of java here
http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
I would like to point out that writing
5.1D or 5.1 : if you don't specify a type letter for a comma number then by default it is double
5 : without the period, by default it is an int
They're format specifiers for float and double literals. When you write 1.0, it's ambiguous as to whether you intend the literal to be a float or double. By writing 1.0f, you're telling Java that you intend the literal to be a float, while using 1.0d specifies that it should be a double. There's also L, which represents long (e.g., 1L is a long 1, as opposed to an int 1)
D stands for double and F stands for float. You will occasionally need to add these modifiers, as 5 is considered an integer in this case, and 3.0 is a double.
As others have mentioned they are the Type definitions, however you will less likely see i or d mentioned as these are the defaults.
float myfloat = 0.5;
will error as the 0.5 is a double as default and you cannot autobox down from double to float (64 -> 32 bits) but
double mydouble = 0.5;
will have no problem
It defines the datatype for the constants 5 and 3.0.