Format numbers in JavaScript similar to C#

后端 未结 18 2296
傲寒
傲寒 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:56

    Firstly, converting an integer into string in JS is really simple:

    // Start off with a number
    var number = 42;
    // Convert into a string by appending an empty (or whatever you like as a string) to it
    var string = 42+'';
    // No extra conversion is needed, even though you could actually do
    var alsoString = number.toString();
    

    If you have a number as a string and want it to be turned to an integer, you have to use the parseInt(string) for integers and parseFloat(string) for floats. Both of these functions then return the desired integer/float. Example:

    // Start off with a float as a string
    var stringFloat = '3.14';
    // And an int as a string
    var stringInt = '42';
    
    // typeof stringInt  would give you 'string'
    
    // Get the real float from the string
    var realFloat = parseFloat(someFloat);
    // Same for the int
    var realInt = parseInt(stringInt);
    
    // but typeof realInt  will now give you 'number'
    

    What exactly are you trying to append etc, remains unclear to me from your question.

提交回复
热议问题