Convert to currency format

后端 未结 6 1185
迷失自我
迷失自我 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 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.

    
    
    
    Number to Money Conversion
    
    
    
    
    
    
    
    
    
    

    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

提交回复
热议问题