/    Sign up×
Community /Pin to ProfileBookmark

JavaScript decimal field

Hello,

I am looking for a JavaScript that make a text field act as a decimal field. Another words if user enters 22, it automatically appends “.00” at the end. Also, it checks if no more than 2 digits are typed after “.” and no more than one “.” is typed. I need it for my project at work, but don’t have time to work on this implementation. If anybody has this functionality, I’d appreciate it very much if you share.

thanks!
camokat

to post a comment
JavaScript

9 Comments(s)

Copy linkTweet thisAlerts:
@VladdyMay 26.2004 — myInput.value = parseFloat(myInput.value).toFixed(2);
Copy linkTweet thisAlerts:
@camokatauthorMay 26.2004 — thanks, but how do I attach it to text field?
Copy linkTweet thisAlerts:
@VladdyMay 26.2004 — You can use onchange event:

onchange="this.value = parseFloat(this.value).toFixed(2)"
Copy linkTweet thisAlerts:
@camokatauthorMay 26.2004 — Actually, what I need is something that checks the field in real time, while user types in the information.
Copy linkTweet thisAlerts:
@camokatauthorMay 26.2004 — thanks Vladdy!

But how do I limit number of digits to 2 after the period, and not allow more than one period?
Copy linkTweet thisAlerts:
@camokatauthorMay 26.2004 — Oh, wait it works! thanks much!
Copy linkTweet thisAlerts:
@camokatauthorMay 26.2004 — One more thing, I want to use characters: >,< or = in front of decimal fields. But when I use these characters I get NaN because it can't convert to float. Is there a workaround?
Copy linkTweet thisAlerts:
@VladdyMay 26.2004 — Not with this approach.

Use regular expressions.

On the side note:

Defining requirements prior to starting realization saves a lot of time/money/effort
Copy linkTweet thisAlerts:
@camokatauthorMay 26.2004 — Yes I know, but I did not realize that NaN would be thown. So how do I use regular expressions with this?
×

Success!

Help @camokat spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...