0

How to convert a double value to a float value without changing its precision.

for example, if I am having double var = 1/4 i.e.(0.25) how to change it to a float type with the value of the variable being 0.25.

Sean
  • 1
  • 1
  • 4
    This is unclear. What's wrong with `(float)var`? – Oliver Charlesworth Feb 21 '15 at 14:02
  • Have you tried casting it to a float? – Gordonium Feb 21 '15 at 14:03
  • 1
    There is no difference in var's value between `double var = 1 / 4` and `double var = 0.25`. There is no way to convert a double value to a float value without losing its precision -- that's a little like asking how to convert red to blue without losing any of the red color. I suggest you read a bit about how floating point values are represented in binary computers; if it doesn't answer your question, it will give you background on how to refine it so we can answer it better. – arcy Feb 21 '15 at 14:06
  • 1
    Just in case this is the problem: You do realize that `double var = 1 / 4` will give you `0.0`, because the division is of integers and only the result (0) is converted to `double`? – RealSkeptic Feb 21 '15 at 14:09
  • @arcy: "There is no difference..." - did you try it? – Oliver Charlesworth Feb 21 '15 at 14:11
  • @RealSkeptic Yes exactly that is happening. – Sean Feb 21 '15 at 14:23
  • Then [this question and its answers](http://stackoverflow.com/q/6568847/4125191) may help you. – RealSkeptic Feb 21 '15 at 14:27
  • @OliverCharlesworth (sigh) I use floating point so rarely that this one of those things I often trip over. Obviously I was thinking about 1.0/4.0, or whatever other way to divide floating point numbers instead of ints. I was focusing on the OP's desire to convert to double "without losing precision". – arcy Feb 21 '15 at 15:29

0 Answers0