Convert double to float in Java

前端 未结 10 823
执念已碎
执念已碎 2020-12-08 18:13

I am facing an issue related to converting double to float. Actually, I store a float type, 23423424666767, in a database, but when we

相关标签:
10条回答
  • 2020-12-08 18:50

    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).

    0 讨论(0)
  • 2020-12-08 18:51

    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.

    0 讨论(0)
  • 2020-12-08 18:57

    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
    
    0 讨论(0)
  • 2020-12-08 18:57

    Float.parseFloat(String.valueOf(your_number)

    0 讨论(0)
提交回复
热议问题