Format numbers in JavaScript similar to C#

后端 未结 18 2114
傲寒
傲寒 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 13:01

    For example:

    var flt = '5.99';
    var nt = '6';
    
    var rflt = parseFloat(flt);
    var rnt = parseInt(nt);
    
    0 讨论(0)
  • 2020-11-22 13:01

    To further jfriend00's answer (I dont't have enough points to comment) I have extended his/her answer to the following:

    function log(args) {
        var str = "";
        for (var i = 0; i < arguments.length; i++) {
            if (typeof arguments[i] === "object") {
                str += JSON.stringify(arguments[i]);
            } else {
                str += arguments[i];
            }
        }
        var div = document.createElement("div");
        div.innerHTML = str;
        document.body.appendChild(div);
    }
    
    Number.prototype.addCommas = function (str) {
        if (str === undefined) {
        	str = this;
        }
        
        var parts = (str + "").split("."),
            main = parts[0],
            len = main.length,
            output = "",
            first = main.charAt(0),
            i;
        
        if (first === '-') {
            main = main.slice(1);
            len = main.length;    
        } else {
        	  first = "";
        }
        i = len - 1;
        while(i >= 0) {
            output = main.charAt(i) + output;
            if ((len - i) % 3 === 0 && i > 0) {
                output = "," + output;
            }
            --i;
        }
        // put sign back
        output = first + output;
        // put decimal part back
        if (parts.length > 1) {
            output += "." + parts[1];
        }
        return output;
    }
    
    var testCases = [
        1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,
        -1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1
    ];
     
    for (var i = 0; i < testCases.length; i++) {
    	log(testCases[i].addCommas());
    }
     
    /*for (var i = 0; i < testCases.length; i++) {
        log(Number.addCommas(testCases[i]));
    }*/

    0 讨论(0)
  • 2020-11-22 13:05

    Using JQuery.

    $(document).ready(function()
     {
        //Only number and one dot
        function onlyDecimal(element, decimals)
        {
            $(element).keypress(function(event)
            {
                num = $(this).val() ;
                num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
                if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
                {
                    event.preventDefault();
    
                }
                if($(this).val() == parseFloat(num).toFixed(decimals))
                {
                    event.preventDefault();
                }
            });
        }
    
         onlyDecimal("#TextBox1", 3) ;
    
    
    
    });
    

    0 讨论(0)
  • 2020-11-22 13:07

    May I suggest numbro for locale based formatting and number-format.js for the general case. A combination of the two depending on use-case may help.

    0 讨论(0)
  • 2020-11-22 13:10

    I made a simple function, maybe someone can use it

    function secsToTime(secs){
      function format(number){
        if(number===0){
          return '00';
        }else {
          if (number < 10) {
              return '0' + number
          } else{
              return ''+number;
          }
        }
      }
    
      var minutes = Math.floor(secs/60)%60;
      var hours = Math.floor(secs/(60*60))%24;
      var days = Math.floor(secs/(60*60*24));
      var seconds = Math.floor(secs)%60;
    
      return (days>0? days+"d " : "")+format(hours)+':'+format(minutes)+':'+format(seconds);
    }
    

    this can generate the followings outputs:

    • 5d 02:53:39
    • 4d 22:15:16
    • 03:01:05
    • 00:00:00
    0 讨论(0)
  • 2020-11-22 13:13

    To get a decimal with 2 numbers after the comma, you could just use:

    function nformat(a) {
       var b = parseInt(parseFloat(a)*100)/100;
       return b.toFixed(2);
    }
    
    0 讨论(0)
提交回复
热议问题