C# get digits from float variable

前端 未结 12 1680
南笙
南笙 2020-12-06 16:26

I have a float variable and would like to get only the part after the comma, so if I have 3.14. I would like to get 14 as an integer. How can I do that?

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 17:04

    This will result in some odd unpredictable values.

    Floating point numbers are not stored as a decimal - the exponent part is a power of 2, not 10.

    This means that some numbers (for instance 1.1) can't be accurately expressed as a float (1.1 ends up something like 1.099999999998)

    The problem is that for some numbers the starting number may not be one of these while the decimal part on its own might be.

    So your number is x.y

    You get the integer part x

    You do x.y - x to get 0.y

    Sometimes x.y can be expressed as a float and 0.y can't, so rather than get y you'll get some big value with lots of 0s or 9s in it.

    @David's 'cheating' way is actually the best way - least prone to this issue anyway.

    However I'd look at why you need to do this - floats are great for very fast maths, but a bit rubbish for accuracy. If accuracy is important use a decimal type instead - that type guarantees that the precise value is stored, but at the cost of slower maths.

提交回复
热议问题