问题
I am trying to format currency by using this code below:
$('#currency').keyup(function(e){
var val = $(this).val();
val = val.replace(/[^0-9]/g,'');
if(val.length >= 2)
val = '$' + val.substring(0,2) + ',' + val.substring(2);
if(val.length >= 6)
val = val.substring(0,7) + val.substring(7);
if(val.length > 7)
val = val.substring(0,7);
$(this).val(val);
});
But that would work only for volume such as "$10,000" or something like that, How can I include thousands, hundreds, and millions in one code?
回答1:
Here is a nice function in vanilla JS that handles things:
var format = function(num){
var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null;
if(str.indexOf(".") > 0) {
parts = str.split(".");
str = parts[0];
}
str = str.split("").reverse();
for(var j = 0, len = str.length; j < len; j++) {
if(str[j] != ",") {
output.push(str[j]);
if(i%3 == 0 && j < (len - 1)) {
output.push(",");
}
i++;
}
}
formatted = output.reverse().join("");
return("$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : ""));
};
However, for jQuery, you could always turn it into a plug-in, or just use it like:
$(function(){
$("#currency").keyup(function(e){
$(this).val(format($(this).val()));
});
});
EDIT I updated the fiddle JSFiddle
回答2:
You can use regex
in solving this problem, note that your input field should prevent user from typing letter/non-digit character, other than replacing all the typed non-digit characters with empty string, doing that is not professional:
$('input').on('input', function(e){
$(this).val(formatCurrency(this.value.replace(/[,$]/g,'')));
}).on('keypress',function(e){
if(!$.isNumeric(String.fromCharCode(e.which))) e.preventDefault();
}).on('paste', function(e){
var cb = e.originalEvent.clipboardData || window.clipboardData;
if(!$.isNumeric(cb.getData('text'))) e.preventDefault();
});
function formatCurrency(number){
var n = number.split('').reverse().join("");
var n2 = n.replace(/\d\d\d(?!$)/g, "$&,");
return "$" + n2.split('').reverse().join('');
}
Demo.
回答3:
Here is an example using jquery plugin:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JQuery FormatCurrency Sample</title>
<script type="text/javascript" src="scripts/jquery-1.2.6.js"></script>
<script type="text/javascript" src="scripts/jquery.formatCurrency.js"></script>
<style type="text/css">
body, div { margin:0px auto; padding:0px; }
.main { margin:40px; }
.sample { float:left; margin:10px; padding:4px; border:1px solid #888; width:350px; }
.sample h3 { margin:-4px; margin-bottom:10px; padding:4px; background:#555; color:#eee; }
.currencyLabel { display:block; }
</style>
<script type="text/javascript">
// Sample 1
$(document).ready(function()
{
$('#currencyButton').click(function()
{
$('#currencyField').formatCurrency();
$('#currencyField').formatCurrency('.currencyLabel');
});
});
// Sample 2
$(document).ready(function()
{
$('.currency').blur(function()
{
$('.currency').formatCurrency();
});
});
</script>
</head>
<body>
<div class="main">
<div class="formPage">
<h1>Format Currency Sample</h1>
<div class="sample">
<h3>Formatting Using Button Click</h3>
<input type="textbox" id="currencyField" value="$1,220.00" />
<input type="button" id="currencyButton" value="Convert" />
<div>
Formatting Currency to an Html Span tag.
<span class="currencyLabel">$1,220.00</span>
</div>
</div>
<div class="sample">
<h3>Formatting Using Blur (Lost Focus)</h3>
<input type="textbox" id="currencyField" class='currency' value="$1,220.00" />
</div>
</div>
</div>
</body>
</html>
Please refer :
https://code.google.com/p/jquery-formatcurrency/
Demo fiddle: jsfiddle.net/2wEe6/72
来源:https://stackoverflow.com/questions/23966148/how-can-i-format-currency-by-using-jquery