[javascript] How to handle floats and decimal separators with html5 input type number

Im building web app which is mainly for mobile browsers. Im using input fields with number type, so (most) mobile browsers invokes only number keyboard for better user experience. This web app is mainly used in regions where decimal separator is comma, not dot, so I need to handle both decimal separators.

How to cover this whole mess with dot and comma?

My findings:

Desktop Chrome

  • Input type=number
  • User enters "4,55" to input field
  • $("#my_input").val(); returns "455"
  • I can not get the correct value from input

Desktop Firefox

  • Input type=number
  • User enters "4,55" to input field
  • $("#my_input").val(); returns "4,55"
  • Thats fine, I can replace comma with dot and get correct float

Android browser

  • Input type=number
  • User enters "4,55" to input field
  • When input loses focus, value is truncated to "4"
  • Confusing to user

Windows Phone 8

  • Input type=number
  • User enters "4,55" to input field
  • $("#my_input").val(); returns "4,55"
  • Thats fine, I can replace comma with dot and get correct float

What are the "best practices" in this kind of situations when user might use comma or dot as decimal separator and I want to keep html input type as number, to provide better user experience?

Can I convert comma to dot "on the fly", binding key events, is it working with number inputs?

EDIT

Currenlty I do not have any solution, how to get float value (as string or number) from input which type is set to number. If enduser enters "4,55", Chrome returns always "455", Firefox returns "4,55" which is fine.

Also it is quite annoying that in Android (tested 4.2 emulator), when I enter "4,55" to input field and change focus to somewhere else, the entered number get truncated to "4".

This question is related to javascript jquery mobile floating-point html-input

The answer is


uses a text type but forces the appearance of the numeric keyboard

<input value="12,4" type="text" inputmode="numeric" pattern="[-+]?[0-9]*[.,]?[0-9]+">

the inputmode tag is the solution


When you call $("#my_input").val(); it returns as string variable. So use parseFloat and parseIntfor converting. When you use parseFloat your desktop or phone ITSELF understands the meaning of variable.

And plus you can convert a float to string by using toFixed which has an argument the count of digits as below:

var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01

I have not found a perfect solution but the best I could do was to use type="tel" and disable html5 validation (formnovalidate):

<input name="txtTest" type="tel" value="1,200.00" formnovalidate="formnovalidate" />

If the user puts in a comma it will output with the comma in every modern browser i tried (latest FF, IE, edge, opera, chrome, safari desktop, android chrome).

The main problem is:

  • Mobile users will see their phone keyboard which may be different than the number keyboard.
  • Even worse the phone keyboard may not even have a key for a comma.

For my use case I only had to:

  • Display the initial value with a comma (firefox strips it out for type=number)
  • Not fail html5 validation (if there is a comma)
  • Have the field read exactly as input (with a possible comma)

If you have a similar requirement this should work for you.

Note: I did not like the support of the pattern attribute. The formnovalidate seems to work much better.


Whether to use comma or period for the decimal separator is entirely up to the browser. The browser makes it decision based on the locale of the operating system or browser, or some browsers take hints from the website. I made a browser comparison chart showing how different browsers support handle different localization methods. Safari being the only browser that handle commas and periods interchangeably.

Basically, you as a web author cannot really control this. Some work-arounds involves using two input fields with integers. This allows every user to input the data as yo expect. Its not particular sexy, but it will work in every case for all users.


I think what's missing in the answers above is the need to specify a different value for the step attribute, which has a default value of 1. If you want the input's validation algorithm to allow floating-point values, specify a step accordingly.

For example, I wanted dollar amounts, so I specified a step like this:

 <input type="number" name="price"
           pattern="[0-9]+([\.,][0-9]+)?" step="0.01"
            title="This should be a number with up to 2 decimal places.">

There's nothing wrong with using jQuery to retrieve the value, but you will find it useful to use the DOM API directly to get the elements's validity.valid property.

I had a similar issue with the decimal point, but the reason I realized there was an issue was because of the styling that Twitter Bootstrap adds to a number input with an invalid value.

Here's a fiddle demonstrating that the adding of the step attribute makes it work, and also testing whether the current value is valid:

TL;DR: Set the a step attribute to a floating-point value, because it defaults to 1.

NOTE: The comma doesn't validate for me, but I suspect that if I set my OS language/region settings to somewhere that uses a comma as the decimal separator, it would work. *note in note*: that was not the case for OS language/keyboard settings *German* in Ubuntu/Gnome 14.04.


Use valueAsNumber instead of .val().

input . valueAsNumber [ = value ]

Returns a number representing the form control's value, if applicable; otherwise, returns null.
Can be set, to change the value.
Throws an INVALID_STATE_ERR exception if the control is neither date- or time-based nor numeric.


Sounds like you'd like to use toLocaleString() on your numeric inputs.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString for its usage.

Localization of numbers in JS is also covered in Internationalization(Number formatting "num.toLocaleString()") not working for chrome


Appearently Browsers still have troubles (although Chrome and Firefox Nightly do fine). I have a hacky approach for the people that really have to use a number field (maybe because of the little arrows that text fields dont have).

My Solution

I added a keyup event Handler to the form input and tracked the state and set the value once it comes valid again.

Pure JS Snippet JSFIDDLE

_x000D_
_x000D_
var currentString = '';_x000D_
var badState = false;_x000D_
var lastCharacter = null;_x000D_
_x000D_
document.getElementById("field").addEventListener("keyup",($event) => {_x000D_
  if ($event.target.value && !$event.target.validity.badInput) {_x000D_
          currentString = $event.target.value;_x000D_
  } else if ($event.target.validity.badInput) {_x000D_
    if (badState && lastCharacter && lastCharacter.match(/[\.,]/) && !isNaN(+$event.key)) {_x000D_
      $event.target.value = ((+currentString) + (+$event.key / 10));_x000D_
      badState = false;_x000D_
    } else {_x000D_
      badState = true;_x000D_
    }_x000D_
  }_x000D_
  document.getElementById("number").textContent = $event.target.value;_x000D_
  lastCharacter = $event.key;_x000D_
});_x000D_
_x000D_
document.getElementById("field").addEventListener("blur",($event) => {_x000D_
 if (badState) {_x000D_
    $event.target.value = (+currentString);_x000D_
    badState = false;_x000D_
  document.getElementById("number").textContent = $event.target.value;_x000D_
  }_x000D_
});
_x000D_
#result{_x000D_
  padding: 10px;_x000D_
  background-color: orange;_x000D_
  font-size: 25px;_x000D_
  width: 400px;_x000D_
  margin-top: 10px;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
#field{_x000D_
  padding: 5px;_x000D_
  border-radius: 5px;_x000D_
  border: 1px solid grey;_x000D_
  width: 400px;_x000D_
}
_x000D_
<input type="number" id="field" keyup="keyUpFunction" step="0.01" placeholder="Field for both comma separators">_x000D_
_x000D_
<span id="result" >_x000D_
 <span >Current value: </span>_x000D_
 <span id="number"></span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Angular 9 Snippet

_x000D_
_x000D_
@Directive({_x000D_
  selector: '[appFloatHelper]'_x000D_
})_x000D_
export class FloatHelperDirective {_x000D_
  private currentString = '';_x000D_
  private badState = false;_x000D_
  private lastCharacter: string = null;_x000D_
_x000D_
  @HostListener("blur", ['$event']) onBlur(event) {_x000D_
    if (this.badState) {_x000D_
      this.model.update.emit((+this.currentString));_x000D_
      this.badState = false;_x000D_
    }_x000D_
  }_x000D_
_x000D_
  constructor(private renderer: Renderer2, private el: ElementRef, private change: ChangeDetectorRef, private zone: NgZone, private model: NgModel) {_x000D_
    this.renderer.listen(this.el.nativeElement, 'keyup', (e: KeyboardEvent) => {_x000D_
      if (el.nativeElement.value && !el.nativeElement.validity.badInput) {_x000D_
        this.currentString = el.nativeElement.value;_x000D_
      } else if (el.nativeElement.validity.badInput) {_x000D_
        if (this.badState && this.lastCharacter && this.lastCharacter.match(/[\.,]/) && !isNaN(+e.key)) {_x000D_
          model.update.emit((+this.currentString) + (+e.key / 10));_x000D_
          el.nativeElement.value = (+this.currentString) + (+e.key / 10);_x000D_
          this.badState = false;_x000D_
        } else {_x000D_
          this.badState = true;_x000D_
        }_x000D_
      }       _x000D_
      this.lastCharacter = e.key;_x000D_
    });_x000D_
  }_x000D_
  _x000D_
}
_x000D_
<input type="number" matInput placeholder="Field for both comma separators" appFloatHelper [(ngModel)]="numberModel">
_x000D_
_x000D_
_x000D_


My recommendation? Don't use jQuery at all. I had the same problem as you. I found that $('#my_input').val() always return some weird result.

Try to use document.getElementById('my_input').valueAsNumber instead of $("#my_input").val(); and then, use Number(your_value_retrieved) to try to create a Number. If the value is NaN, you know certainly that that's not a number.

One thing to add is when you write a number on the input, the input will actually accept almost any character (I can write the euro sign, a dollar, and all of other special characters), so it is best to retrieve the value using .valueAsNumber instead of using jQuery.

Oh, and BTW, that allows your users to add internationalization (i.e.: support commas instead of dots to create decimal numbers). Just let the Number() object to create something for you and it will be decimal-safe, so to speak.


According to w3.org the value attribute of the number input is defined as a floating-point number. The syntax of the floating-point number seems to only accept dots as decimal separators.

I've listed a few options below that might be helpful to you:

1. Using the pattern attribute

With the pattern attribute you can specify the allowed format with a regular expression in a HTML5 compatible way. Here you could specify that the comma character is allowed and a helpful feedback message if the pattern fails.

<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
           title="The number input must start with a number and use either comma or a dot as a decimal character."/>

Note: Cross-browser support varies a lot. It may be complete, partial or non-existant..

2. JavaScript validation

You could try to bind a simple callback to for example the onchange (and/or blur) event that would either replace the comma or validate all together.

3. Disable browser validation ##

Thirdly you could try to use the formnovalidate attribute on the number inputs with the intention of disabling browser validation for that field all together.

<input type="number" formnovalidate />

4. Combination..?

<input type="number" pattern="[0-9]+([,\.][0-9]+)?" 
           name="my-num" formnovalidate
           title="The number input must start with a number and use either comma or a dot as a decimal character."/>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to mobile

How to center a component in Material-UI and make it responsive? NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference Asus Zenfone 5 not detected by computer background: fixed no repeat not working on mobile Check box size change with CSS onClick not working on mobile (touch) Sharing link on WhatsApp from mobile website (not application) for Android Bootstrap 3 Slide in Menu / Navbar on Mobile How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place? Using form input to access camera and immediately upload photos using web app

Examples related to floating-point

Convert list or numpy array of single element to float in python Convert float to string with precision & number of decimal digits specified? Float and double datatype in Java C convert floating point to int Convert String to Float in Swift How do I change data-type of pandas data frame to string with a defined format? How to check if a float value is a whole number Convert floats to ints in Pandas? Converting Float to Dollars and Cents Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Examples related to html-input

Using Pipes within ngModel on INPUT Elements in Angular HTML 5 input type="number" element for floating point numbers on Chrome Html/PHP - Form - Input as array How to locate and insert a value in a text box (input) using Python Selenium? Drop Down Menu/Text Field in one HTML5 pattern for formatting input box to take date mm/dd/yyyy? How to add button inside input How to handle floats and decimal separators with html5 input type number How to set default value to the input[type="date"] Get data from file input in JQuery