C# Math.Round(value / 2). value is decimal. function not working for one specific number 4.5

前端 未结 1 1445
春和景丽
春和景丽 2021-01-25 02:39

I am looking to round decimal, 0.1 to 0.4 round down and 0.5 to 0.9 round up tried these but for some reason if value is 4.5 it rounds to 4 and not 5 all other values work fine.

相关标签:
1条回答
  • 2021-01-25 03:28

    Your first line is using the default type of rounding (known as banker's rounding). Your second line almost gets what you want, but you don't need to include two calls to Math.Round().

    For what you're wanting, it should probably look like this:

    Math.Round((value / 2), 0, MidpointRounding.AwayFromZero)
    // e.g. 3.5 => 4, 4.5 => 5, 5.5 => 6, etc.
    

    Read more about banker's rounding here, and read more about Math.Round() here.

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