javascript - 如何格式化输入到 HTML 文本字段中的文本,如货币?

标签 javascript html css

我有一系列文本域,我想将其格式化为货币。最好,这将在运行中完成,但至少在模糊时完成。我所说的货币格式是 349507 -> $349,507。可能吗?

我更喜欢 HTML/CSS/JS 解决方案,因为我不需要太多解释。我对 jQuery 一点都不熟悉。

非常感谢任何帮助。
Mike

最佳答案

这是我很久以前写的一些代码,用逗号格式化数字。一个例子是 formatNumber(349507, 0, 2, true)"349,507.00"

// Reformats a number by inserting commas and padding out the number of digits
// and decimal places.
//
// Parameters:
//     number:        The number to format. All non-numeric characters are
//                    stripped out first.
//     digits:        The minimum number of digits to the left of the decimal
//                    point. The extra places are padded with zeros.
//     decimalPlaces: The number of places after the decimal point, or zero to
//                    omit the decimal point.
//     withCommas:    True to insert commas every 3 places, false to omit them.
function formatNumber(number, digits, decimalPlaces, withCommas)
{
        number       = number.toString();
    var simpleNumber = '';

    // Strips out the dollar sign and commas.
    for (var i = 0; i < number.length; ++i)
    {
        if ("0123456789.".indexOf(number.charAt(i)) >= 0)
            simpleNumber += number.charAt(i);
    }

    number = parseFloat(simpleNumber);

    if (isNaN(number))      number     = 0;
    if (withCommas == null) withCommas = false;
    if (digits     == 0)    digits     = 1;

    var integerPart = (decimalPlaces > 0 ? Math.floor(number) : Math.round(number));
    var string      = "";

    for (var i = 0; i < digits || integerPart > 0; ++i)
    {
        // Insert a comma every three digits.
        if (withCommas && string.match(/^\d\d\d/))
            string = "," + string;

        string      = (integerPart % 10) + string;
        integerPart = Math.floor(integerPart / 10);
    }

    if (decimalPlaces > 0)
    {
        number -= Math.floor(number);
        number *= Math.pow(10, decimalPlaces);

        string += "." + formatNumber(number, decimalPlaces, 0);
    }

    return string;
}

您可以像这样在 onblur 事件处理程序上使用它:

<input type="text" onblur="this.value = '$' + formatNumber(this.value, 0, 0, true)" />

这将为数字添加逗号并在前面加上美元符号。

关于javascript - 如何格式化输入到 HTML 文本字段中的文本,如货币?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1162711/

相关文章:

javascript - 页面无需登录验证即可登录

javascript - 移动 Safari,scrollIntoView 不起作用

html - CSS 背景图像未加载,但在我检查后加载

javascript - 定义为在命令中输入更多值的添加按钮正在删除所有现有值,有没有办法避免这种情况?

jquery - Fancybox3 Youtube 视频

html - Windows Phone 浏览器上的硬件加速 CSS3 转换

css - Span继承列表样式

javascript - 未捕获的语法错误 : Unexpected token ) on line 5

javascript - 我可以以某种方式将当前运行的 javascript 函数记录到 Chrome 开发者控制台中吗?

html - 文字不在右侧