How do I display a decimal value to 2 decimal places?

前端 未结 17 2144
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 23:24

When displaying the value of a decimal currently with .ToString(), it\'s accurate to like 15 decimal places, and since I\'m using it to represent dollars and ce

17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 23:52

    None of these did exactly what I needed, to force 2 d.p. and round up as 0.005 -> 0.01

    Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p.

    then rounding to ensure we do not have more than 2 d.p.

    Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)
    
    6.665m.ToString() -> "6.67"
    
    6.6m.ToString() -> "6.60"
    

提交回复
热议问题