简体   繁体   English

JavaScript中小数点后的数字限制

[英]Number Restriction after decimal point in javascript

How to restrict the number of digits after the decimal point using "onkeyup" even in javascript? 如何甚至在JavaScript中使用“ onkeyup”来限制小数点后的位数?

I want to restrict the number of digits after the decimal point based on an input already given in the page. 我想基于页面中已经给出的输入来限制小数点后的位数。 if i give the input as 3 then the digits after the decimal points should be only 3. for this i need to use javascript so that at runtime itself output is shown to user and the user should not be able to enter more than 3. 如果我将输入设置为3,则小数点后的数字应仅为3。为此,我需要使用JavaScript,以便在运行时本身向用户显示输出,并且用户输入的数字不能超过3。

You can use the toFixed method: 您可以使用toFixed方法:

var withDecimals = (1*value).toFixed(numberOfDecimals);

Multiplying by 1 makes sure that we are dealing with a number and not some other object, like a string. 乘以1可确保我们处理的是数字,而不是字符串等其他对象。

您可以使用toFixed(Your number)

尝试这个:

your_number = (your_number).toFixed(3);

The objectvalue is the current inputtext object where value is entered. objectvalue是输入值的当前输入文本对象。 id is the object value of the field where precision(no of digits after decimal) is entered. id是输入精度(十进制后的位数)的字段的对象值。

function decimalRestriction(objectValue,id) { var precision=document.getElementById(id).value; 函数decimalRestriction(objectValue,id){var precision = document.getElementById(id).value; var value=objectValue.value; var value = objectValue.value; if(value.match('.')) { var decimaldigits=value.split('.'); if(value.match('。')){var十进制数字= value.split('。'); if(decimaldigits[1].length > precision) objectValue.value= decimaldigits[0]+ '.' if(decimaldigits [1] .length> precision)objectValue.value =十进制数字[0] +'。' + decimaldigits[1].substring(0, precision); +十进制数字[1] .substring(0,precision); } } }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM