最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - formatting money with jquery - Stack Overflow

programmeradmin2浏览0评论

I wrote this little snippet that should format money but its failing on the period for some reason. It keeps adding them every time ...any idea why and is there a better way of doing this

$(".dollar").blur(function() {
    var curval = $(this).val(); 
    if ($(this).val().indexOf("$") != 0) {
        $(this).val("$" + $(this).val());
    } 
    if ($(this).val().indexOf(".") != 0){
        $(this).val($(this).val() + ".00");
    }
});

I wrote this little snippet that should format money but its failing on the period for some reason. It keeps adding them every time ...any idea why and is there a better way of doing this

$(".dollar").blur(function() {
    var curval = $(this).val(); 
    if ($(this).val().indexOf("$") != 0) {
        $(this).val("$" + $(this).val());
    } 
    if ($(this).val().indexOf(".") != 0){
        $(this).val($(this).val() + ".00");
    }
});
Share Improve this question asked Mar 8, 2011 at 20:47 Matt ElhotibyMatt Elhotiby 44.1k91 gold badges224 silver badges328 bronze badges 2
  • 2 indexOf returns -1 if the string is not found. – gen_Eric Commented Mar 8, 2011 at 20:52
  • You are checking if the index of the . is not 0, that is, on the LHS of the value. this would only match something like .50, I suspect you instead simply want to check if a . exists, in which case just check ` indexOf('.') != -1` – idbentley Commented Mar 8, 2011 at 20:53
Add a ment  | 

3 Answers 3

Reset to default 5

I wrote a different dollar formatting snippet that will take any number (1, 1.6, 2.52, 8.2472) and automatically format it to dollar notation ($1.00, $1.60, $2.52, $8.24):

$('.dollars').blur(function(e){
    var curVal = parseFloat($(this).val()),
        curInt = parseInt(curVal, 10),
        curDec = parseInt(curVal*100, 10) - parseInt(curInt*100, 10);

    curDec = (curDec < 10) ? "0" + curDec : curDec;

    if (!isNaN(curInt) && !isNaN(curDec)) {
        $(this).val("$"+curInt+"."+curDec);
    }
});

See it in action here.

You may take a look at the jquery globalization plugin.

The "indexOf" function returns the index into the string. I think you should be testing to see if the result is less than zero.

if ($(this).val().indexOf("$") < 0) {
    $(this).val("$" + $(this).val());
} 
if ($(this).val().indexOf(".") < 0){
    $(this).val($(this).val() + ".00");

edit oops — I had it backwards :-) Less than zero, not greater than or equal to. The latter is what you'd do to find out if the character is in the string, but your code needs to know when it's not in the string.

发布评论

评论列表(0)

  1. 暂无评论