String.Format an integer to use a thousands separator without decimal places or leading 0 for small integers

前端 未结 4 1427
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 13:03

Silly question, I want to format an integer so that it appears with the 1000\'s separator (,), but also without decimal places and without a leading 0.

My attempts s

相关标签:
4条回答
  • 2020-12-02 13:25
    String.Format("{0:#,0} {1:#,0}", 5, 5000); // "5 5,000"
    
    • 0 in a format string means put the digit that belongs here, or else a [leading/trailing] zero [to make things align, etc.]. EDIT: You'll definitely want one as the last digit in the pattern, or a zero value will be rendered as an empty String
    • # means don't put anything into the output unless there's a significant digit here.

    EDIT (thanks @eulerfx):

    • the last portion needs to be a 0 rather than a # (as I initially had it) as a value of zero would otherwise be rendered as a zero-length string.
    0 讨论(0)
  • 2020-12-02 13:28

    Try this:-

    String.Format("{0:n0}",5000) // 5,000
    String.Format("{0:n0}",5) // 5
    String.Format("{0:n0}",0) // 0
    
    0 讨论(0)
  • 2020-12-02 13:33

    Try

    String.Format("{0:#,#}", 4000);
    
    0 讨论(0)
  • 2020-12-02 13:46

    This worked for me.

    String.Format("{0:#,0} {1:#,0}", 5, 5000); // 5 5,000
    
    0 讨论(0)
提交回复
热议问题