Number Restriction after decimal point in javascript - javascript

How to restrict the number of digits after the decimal point using "onkeyup" even in javascript?
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.

You can use the toFixed method:
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.

Try this:
your_number = (your_number).toFixed(3);

You can use toFixed(Your number) for that

The objectvalue is the current inputtext object where value is entered. id is the object value of the field where precision(no of digits after decimal) is entered.
function decimalRestriction(objectValue,id)
{
var precision=document.getElementById(id).value;
var value=objectValue.value;
if(value.match('.'))
{
var decimaldigits=value.split('.');
if(decimaldigits[1].length > precision)
objectValue.value= decimaldigits[0]+ '.' + decimaldigits[1].substring(0, precision);
}
}

Related

Determine precision of number, including trailing zeros

I suspect that this isn't possible, but giving it a try:
Is it possible to determine the number of decimal points of a number, whether or not those decimal points are trailing zeros?
getPrecision(3) // 0
getPrecision(3.2) // 1
getPrecision(2.30) // 2
I've found a couple of solutions for the first two cases (including this: How do I get the decimal places of a floating point number in Javascript?) but nothing for the last case. Converting 3.20 to a string results in "3.2", which doesn't help, and I'm about out of ideas.
Yes, this is possible but only with a trick
First of all, as per your problem statement, if you ask javascript to split and count your float value into 2 integers then it won't include trailing 0s of it.
Let's satisfy our requirement here with a trick ;)
In the below function you need to pass a value in string format and it will do your work
function getPrecision(value){
a = value.toString()
console.log('a ->',a)
b = a.split('.')
console.log('b->',b)
return b[1].length
getPrecision('12.12340') // Call a function
For an example, run the below logic
value = '12.12340'
a = value.toString()
b = a.split('.')
console.log('count of trailing decimals->',b[1].length)
That's it! Just pass your float value in string format and you are done!
Thank you!

Regular expression for decimals

Hi Experts,
I have a requirement where I think regular expressions might help reducing a lot of if statements and conditions in my code.
My requirement is something like this
I have a quantity field that is displayed in the UI( JavaScript) which has a control factor (based on the quantity field's Unit of Measurement) send from the backend .
Example my Quantity = "126.768"
The control factor D = "2" (which means the number of display positions after the decimal point is 2) .
Now I need a regex to find the following
Regex1 should check whether the quantity is having any decimal points at all. If so then it should check whether the value after decimal points are not just zeros (ex sometimes quantity comes without getting formatted with the full length of decimal points 145.000, which in our case should be displayed as 145 in the UI and the control factor D doesn't need to be considered). Also RegEx should consider quantity values like ".590" ".001" etc.
Since I am new to RegEx I am struggling to come up with an expression
I managed to make a very basic RegEx that just check for the "." within the quantity and all the values after the "."
RegEx = /[.]\d*/g
If RegEx1 returns a positive result . Then Regex2 should now check for the value D. It should adjust the decimal points based on D. For example if D = 3 and quantity = 345.26 then the output of regex2 should give 345.260 and similarly is D = 1 then quantity should be 345.3 ( donno whether rounding is possible using RegEx, a solution without rounding is also fine).
Regards,
Bince
The first regex is
"\d*\.\d*[1-9]\d*"
It searches for at least 1 non-zero digit after the dot.
For the second point, you can round with regex only if the digits overcomes the control factor, while for the 0-padding you can't use regex:
function round(num, control) {
var intPart = num.split(".")[0];
var decPart = num.split(".")[1];
decPart = decPart.substring(0, control); //this does the truncation
var padding = "0".repeat(control - decPart.length); //this does the 0-padding
return intPart + "." + decPart + padding;
}
var num1 = "210.012";
var num2 = "210.1";
var control = 2;
console.log(round(num1, control));
console.log(round(num2, control));
You shouldn't need for any check or regex,
there is a Number.prototype.toFixed method that will help you to adjust decimals.
It basically rounds a number to the nearest decimal point and returns a string. If you're working with strings, make sure you cast it before (using Number statically)
console.log(17.1234.toFixed(2)); // round it down
console.log(17.1264.toFixed(2)); // round it up
console.log(17..toFixed(2)); // Integer
console.log(Number("126.768").toFixed(2)); // from string casting

Javascript - Explicit decimal values separated by comma

I have a JavaScript and HTML form to make a different sums and multiplications. In general, the script works fine, but in some cases, it does not apply the decimal separator and does not display decimal values.
This is the JavaScript when it sums the values well calculated in the precedent script with decimal separator (example: 228.8). This script returns the value of the sum 1040+228.8-208 = 1060) but the really result is 1060.8:
function sumResult() {
var bookSumFT = parseInt(document.getElementById("bookSum").value);
var bookRivFT = parseInt(document.getElementById("bookRiv").value)
var bookIVTFT = parseInt(document.getElementById("bookIVT").value)
var bookRitFT = parseInt(document.getElementById("bookRit").value)
document.getElementById("bookAllCalc").value = bookSumFT + bookRivFT + bookIVTFT - bookRitFT;
}
How do I calculate the correct sum with decimal values?
parseInt() will convert your values to integers. That is, without the decimal part.
Use Number() or parseFloat() instead of parseInt()

Read a number value from a div element and round to 2 decimal places

I want to retrive a number value from a div and then round that number to 2 decimal places using jQuery.
So far I have the element name and value:
<div class="value">Price = £133.3223443</div>
I am using the toFixed() method to convert a number into a string then round to 2 decimal places:
var inNum = 12345.6789;
inNum.toFixed(2);
However, I am having trouble trying to read a number within the element on the page (ignoring 'Price'), rather than just rounding a number entered within the jQuery.
Parse it with regexp? :)
http://jsfiddle.net/LERFB/2/ <--- working fiddle
var price = $('div.value').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
alert(parsedPrice.toFixed(2));
You can use text() to get the value from the element, and the split() by £ to get the numerical price. Try this:
var inNum = parseFloat($('.value').text().split('£')[1]).toFixed(2);
Example fiddle
Obviously you will also need some form of verification to ensure that there is a £ character in the string to split by, and that the value retrieved is numerical.
The following regular expression will extract the floating numbers from the string and do a toFixed operation.
var inNum = parseFloat($(".value").text().match(/[\d\.\d]+/i)).toFixed(2);
Please make sure you have the value inside the container all the time.

Only allow a single dot point in input field

I have an input field which has:
$(".double").alphanumeric({allow:" ",ichars:"`~!##$%^&*=_+[]\\{}|;\":,/<>?'-()\/abcdefghijklmnopqrstuvwxyzABCDFEGHIJKLMNOPQRSTUVWXYZ"});
validation applied to it.
I need to further restrict entry so that only a single decimal place can be added e.g. 100.00 or 255.95
The input is used for currency so I need to only allow 1 decimal point. At the moment its allow 100.00.00 which messes up the system!
Thanks
Here is a regex that will only allow positive/negative decimal numbers
^[-]?((\d+)|(\d+\.\d+)|(\.\d+))$
With jquery you can test the value
if (/^[-]?((\d+)|(\d+\.\d+)|(\.\d+))$/.test($(".double").val())) { .... }
A simple function to allow an optional leading + or - and only digits with an optional decimal place is:
function validate(value) {
var re = /^[-+]?\d+(\.\d+)?$/;
return re.test(value);
}
However since you want money, you might want:
var re = /^[-+]?\d+(\.\d\d)?$/;
which will require two digits after the decimal place, if there is one.

Categories

Resources