admin管理员组文章数量:1335427
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
3 Answers
Reset to default 5I 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.
本文标签: javascriptformatting money with jqueryStack Overflow
版权声明:本文标题:javascript - formatting money with jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742235481a2438000.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论