Rounding of float values

前端 未结 2 1596
孤城傲影
孤城傲影 2020-12-15 03:32

I have the double value like 12.256852651 and I want to display it as 12.257 as a float number without converting it in to a string ty

相关标签:
2条回答
  • 2020-12-15 03:50

    I'd first convert to Decimal and then use Math.Round on the result. This conversion is not strictly necessary, but I always feel a bit uneasy if I round to decimal places while using binary floating points.

    Math.Round((Decimal)f, 3, MidpointRounding.AwayFromZero)
    

    You should also look into the choice of MidpointRounding, since by default this uses Banker's round, which is not what you are used to from school.

    0 讨论(0)
  • 2020-12-15 04:02

    If you want to display it, it will be a string and that's what you need to use.

    If you want to round in order to use it later in calculations, use Math.Round((decimal)myDouble, 3).

    If you don't intend to use it in calculation but need to display it, use double.ToString("F3").

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