Format numbers in JavaScript similar to C#

后端 未结 18 2385
傲寒
傲寒 2020-11-22 12:26

Is there a simple way to format numbers in JavaScript, similar to the formatting methods available in C# (or VB.NET) via ToString(\"format_provider\") or

18条回答
  •  生来不讨喜
    2020-11-22 12:49

    http://code.google.com/p/javascript-number-formatter/ :

    • Short, fast, flexible yet standalone. Only 75 lines including MIT license info, blank lines & comments.
    • Accept standard number formatting like #,##0.00 or with negation -000.####.
    • Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol.
    • Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.
    • Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.
    • Auto number rounding.
    • Simple interface, just supply mask & value like this: format( "0.0000", 3.141592)

    UPDATE

    As say Tomáš Zato here one line solution:

    (666.0).toLocaleString()
    numObj.toLocaleString([locales [, options]])
    

    which described in ECMA-262 5.1 Edition:

    • http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4.3
    • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

    and will work in future versions of browsers...

提交回复
热议问题