I have an asp textbox and I would like to set up a javascript function to only allow people to enter decimal values with 2 numbers beyond the decimal point. For example:

`43432131 - good`

`54525582.23 - good`

`3423.3 - good`

`.23 - good`

`45573490.343 - bad`

`34.34.34 - bad`

`345..23 - bad`

You get the idea. I have an existing function with a regex that sort of works.

```
function fnCurrencyOnly(o) {
var sValue = o.value;
var sKey = String.fromCharCode(window.event.keyCode);
if (document.selection.createRange().text == sValue) {
sValue = sKey;
}
else {
sValue = sValue + sKey;
}
var re = new RegExp("^\\d+(?:\\.\\d{0,2})?$");
if (!sValue.match(re))
window.event.returnValue = false;
}
```

And I set that to my button in c# code behind with a

```
private void AddAttributes()
{
txtRate.Attributes.Add("onkeypress", "fnCurrencyOnly(this)");
}
```

And this works as long as you are typing the whole number from beginning to end. But if you have 100.00 for example, and stick your cursor between the 1 and zero and type 2, to try and make the value 1200.00 (which is perfectly valid) it won't let you type the 2. The reason for this is in the javascript function, it does the svalue + skey thing, which just tacks what you are typing on to the end. So in this case it is actually validating 100.002, which of course is wrong. I couldn't figure out a way to check on keypress what the value is going to be and check it against the regex. I know I can do it on keyup, but then how do I revert back to the old value if it is not valid?

Well I found my own answer:

```
function doGetCaretPosition(oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
oField.focus(); // Set focus on the element
var oSel = document.selection.createRange(); // To get cursor position, get empty selection range
oSel.moveStart("character", -oField.value.length); // Move selection start to 0 position
iCaretPos = oSel.text.length; // The caret position is selection length
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == "0") {
iCaretPos = oField.selectionStart;
}
// Return results
return (iCaretPos);
}
function fnCurrencyOnly(o) {
var sValue = o.value;
var sKey = String.fromCharCode(window.event.keyCode);
var pos = doGetCaretPosition(o);
if (document.selection.createRange().text == sValue) {
sValue = sKey;
}
else {
sValue = sValue.substr(0, pos) + sKey + sValue.substr(pos);
}
var re = new RegExp("^\\d+(?:\\.\\d{0,2})?$");
if (!sValue.match(re))
window.event.returnValue = false;
}
```

From: https://codinglifestyle.wordpress.com/2009/04/24/currency-textbox-with-javascript/#comment-2064

Works perfectly, except you can still copy and paste invalid stuff in the box. Will try to find a solution for that next.

Similar Questions

I'd like to round up to 2 decimal places, but only if necessary. Input: 10 1.7777777 9.1 Output: 10 1.78 9.1 How can I do this in JavaScript?

Does anyone know of an elegant way to get the decimal part of a number only? In particular I am looking to get the exact number of places after the decimal point so that the number can be formatted ap

Texbox restrict entering characters and symbols and only allow numeric values with only one decimal point.maximum length 4 and one value after decimal point.For eg: .2,12.3,1444 Here is the code in ht

I have a function that converts decimal to binary and returns a char * of a binary: void decimal2binary(int decimalNum, int size, char * charPtr){ int decimalTemp = decimalNum; int modNum; for(int siz

I would like to know how can I output a number with 2 decimal places, without rounding the original number. For example: 2229,999 -> 2229,99 I already tried: FORMAT(2229.999, 2) CONVERT(2229.999,

What is the best way to restrict number-only input for textboxes? I am looking for something that allows decimal points. I see a lot of examples. But have yet to decide which one to use. Update from

I need a regular expression that validates a decimal number, but doesn't require any symbol befor number . ie. .2 (fine) .12 (fine) 12 (fine) 12.0 (fine) 12.12 (fine) But 12.123 (not allow) -12.12(no

I want to allow only whole values and not decimal to the textbox in vb.net. Can anyone help me how to check validation on that.

Possible Duplicate: round double to two decimal places in java I want to round up the double value upto 2 decimal points. for example: I have double d=2; and the result should be result =2.00

I have a SSRS report with full of number fields. I would like to have that to be displayed as in one decimal. i tried to use F1. it gives me only one decimal points in html rendering, but in excel exp

I wanted to display a number to 2 decimal places. I thought I could use toPrecision(2) in JavaScript . However, if the number is 0.05, I get 0.0500. I'd rather it stay the same. See it on JSbin. What

I could develop the following code in Javascript that allows only digits to a given HTML TextField. function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode >

I want to compare version numbers of apps/software which sometimes may have two decimal points such as: 1.0 1.1 1.0.01 1.0.1 2.0 2.5 3.0 etc. etc.. What would be the correct way of comparing these n

I use this code for decimal validation.It was working fine.but it allow to enter the alphabets into the text box. when i exit from the text box then only the error message will show nearby textbox.I n

I want to be able to retrieve a number value from a cookie but limit the number to 2 decimal places. The value is stored in a cookie as a result of a change function that calculates, dynamically, a pr

This question already has an answer here: JavaScript: formatting number with exactly two decimals 13 answers How do you round to 1 decimal place in Javascript? 8 answers How am I to get sec

How to find place of decimal point in a decimal number in SQL Server using sql query example: 123567.89 output:7

I have a UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal mark e.g. 2.5 OK 2..5 NOT

I have a variable of decimal type and I want to check the number of digits before decimal point in it. What should I do? For example, 467.45 should return 3.

I have division like this: number / 1000.0 Sometimes it gives answers like 96.0000000001, sometimes the division works as expected. I want to limit my number to a maxim of two decimal places and with

I want to round my decimal value like 2.2222 to 2.23. When I use round, decimal a = Math.Round((decimal)2.222, 2); When I use ceiling, it cause 3 decimal c = Math.Ceiling((decimal)2.22); How can I g

Possible Duplicate: How do you round to 1 decimal place in Javascript? The following code, displays the total distance covered, on a particular route, displayed on google maps. I managed to convert

Have decimal amount, want to trim to 2 decimal places if present

I want my text boxes which are binded to money (SqlServer) entity fields, to show just two decimal places instead of four places. I use DevExpress textEdit and CalcEdit boxes with the following displa

I want regex in javascript for validating number 10.89. It should allow 10.89 and should not allow 10.899 i.e. it should allow only upto two decimal places. It should allow only one period i.e. '.' 10

Possible Duplicate: Simple regular expression for a decimal with a precision of 2? i want to know regular expression that would allow only integers and decimal numbers of any length starting from 0

i need two decimal places for zero , now i have only number zero , should i use decimal function ? but i don't how to integrate to my previous round and sum . round(sum(NUS),2) AS NUS

Possible Duplicate: How do I format numbers to have only two decimal places? I have looked all over for a solution. Say i have a variable with a number like this: $price1 = 1597; $price2 = 1497.85;

I want to remove all the decimal points from a decimal value and add a '%' at the end. I am trying with the following code. <%:string.Format({0:0},i.discount) %> this makes 10.0000 to 10. But

In window textbox, I'd like to just allow 2 decimal points only. I could set text box only numeric but don't know how to limit 2 decimal points. For example, 743.56 My code is below Private Sub txtP

I have a textbox bound to some decimal value. Now, if I type something in it like 100 and clear it completely (empty). I save the data and it saves 1 in decimal value. Similarly if I tried 200 and cle

I need a function to transform decimal values of years in years, months and days. Ex: 1.5 years = 1 year, 6 month. 2.2527397260273973 years = 2 years, 3 months and 1 day. I started with this function:

What can I use as a decimal type in JavaScript? It's not supported (0.1 + 0.2 !== 0.3), and I need it for representing exact values in a banking/financial application. See The State and Future of Java

Hi i am new Java platform. I want to allow only 18 digit before decimal(.) and after decimal i want to enter only two number. For that have used that code snippet but it doesn't work for me. if(detec

Working on 10g. I have a regexp that returns the records numeric values, but in some cases returns multiple decimal points such as 68.70125195853.50 What I need is a way to only return the two decimal

When displaying the value of a decimal currently with .ToString(), it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decima

I want to allow only numbers in a text input field. so this is what I did : $(document).on(keypress, .numeric, function (e) { if(($(this).attr(class)).indexOf(price) >= 0) { if (e.which !=

How to extract a number after the decimal point using BigDecimal ? BigDecimal d = BigDecimal.valueOf(1548.5649); result : extract only : 5649

Please help me make regular expression for positive decimal number with 0, 1 or 2 decimal places. It must allow comma and dot. For example it must allow: 0,01 0.01 0,1 1 1.1 1,11 but not allow: -1 0.

Given the base 36 number YPAYPA, is there a library function in Java that would convert this to a decimal number?

I have a function which I use to limit form inputs to numbers only, or number and decimals depending on the field. Allowing decimals and numbers is easy enough, but I am trying to take it a step furth

Please Help me in writing a C program for my question. Ques- You dont have %f in C. how to write a C program to print decimal number upto 2 decimal places without using %f?

vol = Decimal.Round(exposure.Volatility, 5); This won't let me round exposure.Volatility to a decimal b/c it say's conversion from decimal? to decimal cannot take place. How do I round that number

I have a decimal function: public decimal NGD(long TotalPages, long XHits, long YHits, long BothHits) { return ((Math.Max(XHits, YHits)-BothHits)/(TotalPages - Math.Min(XHits, YHits))); } upon printi

Is it possible to store commas instead of points for decimal fields in a PostgreSQL database?

i want to show only two decimal places in my edit text, ofc i wanna show currency in edit text but limiting its value to 2 digits after decimal. I have seen some solutions using regular expression but

I create a function to compare the price of my item. This is my function: public static decimal ComparePrice(decimal Price, decimal WebsitePrice) { decimal ZERO_PRICE = 0.00000M; if(Price == ZERO_PRIC

Im trying to write a function that takes my decimal degrees (lat or long) and converts them to DMS degrees minutes seconds. I know I am meant to times the decimal point number by 60 then it's decimal

I have a situation where all records in a CSV I'm parsing are currency, but the values are not separated by a decimal point. So for instance, value '1234' is actually '12.34', and '12345' is '123.45'.

I have a Wpf application with some textbox for decimal input. I would that when I press dot key (.) on numeric keypad of pc keyboard it send the correct decimal separator. For example, on Italian la