如何使用JavaScript进行数字格式化?

时间:2022-02-18 01:47:23

I want to use JavaScript to restrict input on a text box to currency number formatting. For example:

我想使用JavaScript将文本框上的输入限制为货币编号格式。例如:

<input type="text" value="2,500.00" name="rate" />

As given above, the text box should accept only numbers, commas and a period.

如上所述,文本框应仅接受数字,逗号和句点。

But, after the period it should accept two digits after numbers.

但是,在这段时间之后,它应该在数字后接受两位数。

How do I accomplish this? Please clarify.

我该如何做到这一点?请澄清。

  • Gnaniyar Zubair

4 个解决方案

#1


parseFloat can convert a string to a float and toFixed can set how many decimal places to keep.

parseFloat可以将字符串转换为float,而toFixed可以设置要保留的小数位数。

function numToCurrency(num){
    return parseFloat(num).toFixed(2);
}


numToCurrency("4.2334546") // returns 4.23

#2


If you want to do validation for your textbox, you can use Regular Expressions. If you want to restrict the input from the user, you can trap the keystrokes and filter out the ones you want them to enter using the onKeyDown event of the textbox.

如果要对文本框进行验证,可以使用正则表达式。如果要限制用户的输入,可以使用文本框的onKeyDown事件捕获按键并过滤掉要输入的按键。

#3


These jQuery plugins can help..

这些jQuery插件可以帮助..

http://www.texotela.co.uk/code/jquery/numeric/

http://plugins.jquery.com/project/aphanumeric

#4


You could use a jQuery's plugin called Alphanumeric

您可以使用名为Alphanumeric的jQuery插件

jQuery AlphaNumeric is a javascript control plugin that allows you to limit what characters a user can enter on textboxes or textareas. Have fun.

jQuery AlphaNumeric是一个javascript控件插件,允许您限制用户可以在文本框或textareas上输入的字符。玩得开心。

#1


parseFloat can convert a string to a float and toFixed can set how many decimal places to keep.

parseFloat可以将字符串转换为float,而toFixed可以设置要保留的小数位数。

function numToCurrency(num){
    return parseFloat(num).toFixed(2);
}


numToCurrency("4.2334546") // returns 4.23

#2


If you want to do validation for your textbox, you can use Regular Expressions. If you want to restrict the input from the user, you can trap the keystrokes and filter out the ones you want them to enter using the onKeyDown event of the textbox.

如果要对文本框进行验证,可以使用正则表达式。如果要限制用户的输入,可以使用文本框的onKeyDown事件捕获按键并过滤掉要输入的按键。

#3


These jQuery plugins can help..

这些jQuery插件可以帮助..

http://www.texotela.co.uk/code/jquery/numeric/

http://plugins.jquery.com/project/aphanumeric

#4


You could use a jQuery's plugin called Alphanumeric

您可以使用名为Alphanumeric的jQuery插件

jQuery AlphaNumeric is a javascript control plugin that allows you to limit what characters a user can enter on textboxes or textareas. Have fun.

jQuery AlphaNumeric是一个javascript控件插件,允许您限制用户可以在文本框或textareas上输入的字符。玩得开心。