Convert to currency format

后端 未结 6 1174
迷失自我
迷失自我 2020-12-06 03:43

Is there a built in function of JavaScript to convert a string into a currency format?

For example

var a = \'1234\';
a.convertToCurrency();   // retu         


        
相关标签:
6条回答
  • 2020-12-06 03:55

    Here's another approach which accounts for cents:

    <!DOCTYPE html>
    <head>
    <meta charset="utf-8">
    <title>Money Conversion</title>
    
    <script type="text/javascript">
    function numberToCurrency(amount) {
    
        var wholeDigits;
        var thousandsSeparator = ","
        var centSeparator = "."
        var currencyNum = "";
    
        if(amount.indexOf(".") != -1) {
            var hasCents = true;
        } else {
            var hasCents = false;
        }
    
        if (hasCents == true) {
            var num = amount.split(".");
            var wholeDigits = num[0].split("");
            var centAmount = num[1];
            var centDigits = num[1].split("");
    
            if (centDigits.length == 0) {
                centDigits += "00";
            }
            if ((centDigits.length > 0) && (centDigits.length < 2)) {
                centDigits += "0";
            }
    
        } else {
            centDigits = "";
            centSeparator = "";
            wholeDigits = amount.split("");
        }
    
        var countDigits = wholeDigits.length;
    
        var revDigits = wholeDigits.reverse();
    
        for(var i=0; i<countDigits; i++) {
                if ((i%3 == 0) && (i !=0)) {
                    currencyNum += thousandsSeparator+revDigits[i];
                } else {
                    currencyNum += wholeDigits[i];
                }
        };
    
        var revCurrency = currencyNum.split("").reverse().join("");
    
        var finalCurrency = "$"+revCurrency+centSeparator+centAmount;
    
        return finalCurrency;
    }
    </script>
    
    </head>
    <body>
    
    
    <script type="text/javascript">
    
    document.write(numberToCurrency('12326563523.37'));
    
    </script>
    
    </body>
    </html>
    

    It does the trick, though it doesn't round the cent amounts or strip off extras past 2 digits.

    0 讨论(0)
  • 2020-12-06 03:59

    I have decided to completely rewrite example I did in 2009. Please check diff if interested in older version. In order to achieve functionality like previous answer, I have extracted a part of the Money library I am working on.

    I also don't remember why I have recreated toFixed last time as that method was already present. This time it is not included.

    Instead of messing with String and Number objects in javascript, like last time, I am creating new, Money, object.

    (function() {
      window.Money = (function() {
    
        Money.prototype.amount = 0.0;
        Money.prototype.fraction_count = 2;
        Money.prototype.fraction_separator = ",";
        Money.prototype.separate_thousands = true;
        Money.prototype.symbol = "€";
        Money.prototype.symbol_position = "front";
        Money.prototype.symbol_spacing = false;
        Money.prototype.thousands_separator = ".";
    
        function Money(amount, options) {
          var o;
          if (options == null) {
            options = {};
          }
          for (o in options) {
            this[o] = options[o];
          }
          amount = parseFloat(amount);
          if (!isNaN(amount)) {
            this.amount = amount;
          }
          this.format();
        }
    
        Money.prototype.format = function() {
          this.string_amount = this.amount.toFixed(this.fraction_count);
          if (this.separate_thousands) {
            this.string_amount = this.separateThousands();
          }
          return this.string = this.addSymbol();
        };
    
        Money.prototype.separateThousands = function() {
          var after_dot, before_dot, pattern, _ref;
          _ref = this.string_amount.split("."), before_dot = _ref[0], after_dot = _ref[1];
          pattern = /(-?\d+)(\d{3})/;
          while (pattern.test(before_dot)) {
            before_dot = before_dot.replace(pattern, "$1" + this.thousands_separator + "$2");
          }
          return [before_dot, after_dot].join(this.fraction_separator);
        };
    
        Money.prototype.addSymbol = function() {
          var string;
          string = [this.string_amount];
          string.splice((this.symbol_position === "front" ? 0 : 1), 0, this.symbol);
          return string.join(this.symbol_spacing ? " " : "");
        };
    
        return Money;
    
      })();
    

    Now, I do need to modify Number and/or String objects slightly and add toMoney method.

    Number.prototype.toMoney = function(options) {
      return new Money(this, options);
    };
    
    String.prototype.toMoney = function(options) {
      return new Money(this, options);
    };
    

    So, finally, we can convert String and/or Number to Money and write it out as String again.

    x = "1234567890.0987654321".toMoney();
    y = 1234567890.0987654321.toMoney({fraction_count: 5, symbol: "$", symbol_position: "back"});
    
    console.log(x);
    // Money {amount: 1234567890.0987654, string_amount: "1.234.567.890,10", string: "€1.234.567.890,10"}
    
    console.log(x.string)
    // €1.234.567.890,10 
    
    console.log(y);
    // Money {fraction_count: 5, symbol: "$", symbol_position: "back", amount: 1234567890.0987654, string_amount: "1.234.567.890,09877"…}
    
    console.log(y.string)
    // 1.234.567.890,09877$ 
    

    I think this solution is much better than the last one I wrote. For working example check jsFiddle.

    0 讨论(0)
  • 2020-12-06 04:08
    var a = 1234.12;
    var c = '$' + a.toLocaleString();
    
    0 讨论(0)
  • 2020-12-06 04:09

    Seems like a lot of work to just parse out a string and figure out where to put the commas.

    Here's a little script I put together this morning that will do the trick for whole numbers:

    Call the function numberToCurrency and pass your value as (amount), and it will put the commas where they should be.

    <!DOCTYPE html>
    <head>
    <meta charset="utf-8">
    <title>Number to Money Conversion</title>
    <script>
        function numberToCurrency(amount) {
    
            var thousandsSeparator = ","
            var currencyNum = "";
            var amountString = amount.toString();
            var digits = amountString.split("");
    
            var countDigits = digits.length;
            var revDigits = digits.reverse();
    
            for(var i=0; i<countDigits; i++) {
                if ((i%3 == 0) && (i !=0)) {
                    currencyNum += thousandsSeparator+revDigits[i];
                } else {
                    currencyNum += digits[i];
                }
            };
    
            var revCurrency = currencyNum.split("").reverse().join("");
    
            var finalCurrency = "$"+revCurrency;
    
            return finalCurrency;
        }
    </script>
    </head>
    <body>
    
    <script>
    document.write(numberToCurrency('1238868934324'));
    </script>
    
    
    </body>
    </html>
    

    You can act on this in a loop taking variables as well -- I threw together a stacked bar chart in Raphael that has the tooltips displaying formatted dollar amounts, taken from straight numbers in an array, so I don't have to fiddle with all the quotes 'n' such. Aside from the black bubble backgrounds being progressively mis-aligned when I mouse over the stacks in each bar, it works pretty well - still having trouble with the labels - labeliser seems to have issues. Just a test sample, really, but for converting numbers to currency, it does the trick.

    I've also done a script that detects for cents and appends a "0" if there's just one digit after the ".", but I haven't tested that as extensively, and there are numerous different tests I could imagine you'd need to do in addition. I'll post the working copy shortly and you can play with it.

    Here's what I did with Raphael: http://lifeistryingtotellyousomething.info/raphael/raphael-stacked-column-demo-2000.html

    0 讨论(0)
  • 2020-12-06 04:12

    This we did in one of our project long back. I just find out the code . Our application was in asp.net. Function dollarAmount does the work

    function checkNum(data) {      // checks if all characters
            var valid = "0123456789.";     // are valid numbers or a "."
            var ok = 1; var checktemp;
            for (var i=0; i<data.length; i++) {
            checktemp = "" + data.substring(i, i+1);
            if (valid.indexOf(checktemp) == "-1") return 0; }
            return 1;
        }
    
        function dollarAmount(form, field, appendZero) 
        { 
            Num = "" + eval("document." + form + "." + field + ".value");
    
            if(Num=="")
            {
                eval("document." + form + "." + field + ".value = '" + 0 + "';");
                return;
            }
    
            dec = Num.indexOf(".");
    
            end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : "");
    
            Num = "" + parseInt(Num);
    
            var temp1 = "";
            var temp2 = "";
            //var appendZero=1;
    
            if (checkNum(Num) == 0) {
            //alert("This does not appear to be a valid number.  Please try again.");
            }
            else {
    
                if(appendZero==1 || end !="")
                {
                    if (end.length == 2) end += "0";
                    if (end.length == 1) end += "00";
                    if (end == "") end += ".00";
                }
    
            var count = 0;
            for (var k = Num.length-1; k >= 0; k--) {
            var oneChar = Num.charAt(k);
            if (count == 3) {
            temp1 += ",";
            temp1 += oneChar;
            count = 1;
            continue;
            }
            else {
            temp1 += oneChar;
            count ++;
            }
            }
            for (var k = temp1.length-1; k >= 0; k--) {
            var oneChar = temp1.charAt(k);
            temp2 += oneChar;
            }
            temp2 = temp2 + end;
            eval("document." + form + "." + field + ".value = '" + temp2 + "';");
            }
        }
    

    We called this function like this

    txtBox.Attributes.Add("OnBlur", "return DollarAmount('" + txtBox.ID + "',0)");
    

    Also after googling I found this links

    a) Use JavaScript to Format Currency within Your Web Page

    b) Currency Format

    Also I guess that JQuery may have some plugin for serving the purpose Currency: an unobstrusive automatic and real time currency conversion

    But I doubt if any inbuilt function is available in javascript. Please let me know if you found any. I would love to know.

    Thanks .

    0 讨论(0)
  • 2020-12-06 04:12

    Although this is an old post. Nonetheless, this worked in for me in my own case:

    var a = parseInt("1234");
    console.log("$"+number_format(a));
    
    var number_format = function(total) {
       return total.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    };
    
    0 讨论(0)
提交回复
热议问题