What kind of data (double, float) should I use when representing a temperature?


My question is regarding the use of Double and Float in Java exercises when having to declare a temperature (Celsius scale). Which one should I use in this case?

I declare as Double , but the teacher correcting the exercise in class ended up using Float .

I know that between these two data the difference is the accuracy they present, but what I still can not understand is when each of them, and for what purposes the Double and Float are used. >     

asked by anonymous 07.09.2018 / 21:00

2 answers


There is no specific type suitable, in this case some can be used.

In fact, if you are going to create types to handle these temperatures and you are going to use a sophisticated infrastructure to represent them, the inner type that will save the numbers matters little. You could use some strategies and depend on what you expect to accomplish. It may even be that simple float solves easy.

If you are going to use a generic type to represent, you can even use int , but probably the easiest is to use a float that already has the decimal part. With a int would have to always make a division to get the decimal part, make accounts to suit the scale you are using, have to be careful and should not be worth for basic use and for more sophisticated use I think the solution previous is better.

Nothing prevents you from using double , but I find it overkill for this sort of thing. float saves memory and has more than enough precision for something simple like that. You can not say it's wrong, but it would not be the first choice.

The difference between them is just the same precision, which obviously makes the most accurate being larger (8 bytes versus 4). Do not confuse with accuracy.

If you had the statement to use something that takes up less space, you might even think of other things, especially if you have a requirement for accuracy. It seems to me that none of this is required, so float is better in real use, but you can argue that double does not hurt unless it's a token memory, which changes little in most cases.

In this case, I doubt that BigDecimal is required, but only you can answer if you must have accuracy beyond the precision that float already gives. See more at What is the correct way to use float, double, and decimal types? .

07.09.2018 / 22:43

Let me copy some things I posted in this answer :


float and double are implemented according to the IEEE 754 standard , used by virtually all modern programming languages that work with 32-bit or 64-bit floating-point numbers.


The float is represented with 32 bits of this form (wikipedia image):













The equations of double are these:


(a) 07.09.2018 / 23:06