[html] Force decimal point instead of comma in HTML5 number input (client-side)

I have seen that some browsers localize the input type="number" notation of numbers.

So now, in fields where my application displays longitude and latitude coordinates, I get stuff like "51,983" where it should be "51.982559". My workaround is to use input type="text" instead, but I'd like to use the number input with correct display of decimals.

Is there a way to force browsers to use a decimal point in the number input, regardless of client-side local settings?

(It goes without saying that in my application I anyway correct this on the server side, but in my setup I also need it to be correct on the client side (because of some JavaScript)).

Thanks in advance.

UPDATE As of right now, checking in Chrome Version 28.0.1500.71 m on Windows 7, the number input just does not accept decimals formatted with a comma. Proposed suggestions with the stepattribute do not seem to work.

http://jsfiddle.net/AsJsj/

This question is related to html google-chrome input numbers decimal

The answer is


I have written a custom piece of code to do this

If you want to replace , with ., remove translate_decimals functions completely.

_x000D_
_x000D_
var input = document.querySelector('input[role="custom-number"]');_x000D_
var bincr = document.querySelector('button[role="increment"]');_x000D_
var bdecr = document.querySelector('button[role="decrement"]');_x000D_
_x000D_
function translate_decimals(side = 0)_x000D_
{_x000D_
 input.value = (side == ',' ? input.value.replace('.',',') : input.value.replace(',','.'));_x000D_
}_x000D_
translate_decimals(',');_x000D_
_x000D_
bincr.addEventListener('click', ()=>{_x000D_
 if (input.hasAttribute('max'))_x000D_
 {_x000D_
  if (input.value.substr(0,input.getAttribute('max').length) == input.getAttribute('max').substr(0,input.getAttribute('max').length))_x000D_
  {_x000D_
   return;_x000D_
  }_x000D_
  else_x000D_
  {_x000D_
   translate_decimals('.');_x000D_
   let temp = input.value;_x000D_
   input.value = "";_x000D_
   input.value = (input.hasAttribute('step') ? (parseFloat(temp) + parseFloat(input.getAttribute('step'))) : temp++);_x000D_
   translate_decimals(',');_x000D_
  }_x000D_
 }_x000D_
});_x000D_
_x000D_
bdecr.addEventListener('click', ()=>{_x000D_
 if (input.hasAttribute('min'))_x000D_
 {_x000D_
  if (input.value.substr(0,input.getAttribute('min').length) == input.getAttribute('min').substr(0,input.getAttribute('min').length))_x000D_
  {_x000D_
   return;_x000D_
  }_x000D_
  else_x000D_
  {_x000D_
   translate_decimals('.');_x000D_
   input.value = (input.hasAttribute('step') ? (input.value - input.getAttribute('step')) : input.value--);_x000D_
   translate_decimals(',');_x000D_
  }_x000D_
 }_x000D_
});
_x000D_
/* styling increment & decrement buttons */_x000D_
button[role="increment"],_x000D_
button[role="decrement"] {_x000D_
 width:32px;_x000D_
}
_x000D_
<input type="text" role="custom-number" step="0.01" min="0" max="0" lang="en" value="1.99">_x000D_
<button role="increment">+</button>_x000D_
<button role="decrement">-</button>
_x000D_
_x000D_
_x000D_


Have you considered using Javascript for this?

$('input').val($('input').val().replace(',', '.'));


HTML step Attribute

<input type="number" name="points" step="3">

Example: if step="3", legal numbers could be -3, 0, 3, 6, etc.

 

Tip: The step attribute can be used together with the max and min attributes to create a range of legal values.

Note: The step attribute works with the following input types: number, range, date, datetime, datetime-local, month, time and week.


1) 51,983 is a string type number does not accept comma

so u should set it as text

<input type="text" name="commanumber" id="commanumber" value="1,99" step='0.01' min='0' />

replace , with .

and change type attribute to number

$(document).ready(function() {
    var s = $('#commanumber').val().replace(/\,/g, '.');   
    $('#commanumber').attr('type','number');   
    $('#commanumber').val(s);   
});

Check out http://jsfiddle.net/ydf3kxgu/

Hope this solves your Problem


I needed to ensure values can still be entered with a comma instead of a point as a decimal separator. This seems to be an age-old problem. Background info can be found following these links:

I finally solved it with a little bit of jQuery. Replacing the commas with dots onChange. This seems to be working good so far in latest Firefox, Chrome and Safari.

$('input[type=number]').each(function () {

  $(this).change(function () {

    var $replace = $(this).val().toString().replace(/,/g, '.');

    $(this).val($replace);

  })

});

With the step attribute specified to the precision of the decimals you want, and the lang attribute [which is set to a locale that formats decimals with period], your html5 numeric input will accept decimals. eg. to take values like 10.56; i mean 2 decimal place numbers, do this:

<input type="number" step="0.01" min="0" lang="en" value="1.99">

You can further specify the max attribute for the maximum allowable value.

Edit Add a lang attribute to the input element with a locale value that formats decimals with point instead of comma


According to the spec, You can use any as the value of step attribute:

<input type="number" step="any">

I don't know if this helps but I stumbled here when searching for this same problem, only from an input point of view (i.e. I noticed that my <input type="number" /> was accepting both a comma and a dot when typing the value, but only the latter was being bound to the angularjs model I assigned to the input). So I solved by jotting down this quick directive:

.directive("replaceComma", function() {
    return {
        restrict: "A",
        link: function(scope, element) {
            element.on("keydown", function(e) {
                if(e.keyCode === 188) {
                    this.value += ".";
                    e.preventDefault();
                }
            });
        }
    };
});

Then, on my html, simply: <input type="number" ng-model="foo" replace-comma /> will substitute commas with dots on-the-fly to prevent users from inputting invalid (from a javascript standpoint, not a locales one!) numbers. Cheers.


I found a blog article which seems to explain something related:
HTML5 input type=number and decimals/floats in Chrome

In summary:

  • the step helps to define the domain of valid values
  • the default step is 1
  • thus the default domain is integers (between min and max, inclusive, if given)

I would assume that's conflating with the ambiguity of using a comma as a thousand separator vs a comma as a decimal point, and your 51,983 is actually a strangely-parsed fifty-one thousand, nine hundred and eight-three.

Apparently you can use step="any" to widen the domain to all rational numbers in range, however I've not tried it myself. For latitude and longitude I've successfully used:

<input name="lat" type="number" min="-90.000000" max="90.000000" step="0.000001">
<input name="lon" type="number" min="-180.000000" max="180.000000" step="0.000001">

It might not be pretty, but it works.


one option is javascript parseFloat()... never do parse a "text chain" --> 12.3456 with point to a int... 123456 (int remove the point) parse a text chain to a FLOAT...

to send this coords to a server do this sending a text chain. HTTP only sends TEXT

in the client keep out of parsing the input coords with "int", work with text strings

if you print the cords in the html with php or similar... float to text and print in html


Sadly, the coverage of this input field in the modern browsers is very low:

http://caniuse.com/#feat=input-number

Therefore, I recommend to expect the fallback and rely on a heavy-programmatically-loaded input[type=text] to do the job, until the field is generally accepted.

So far, only Chrome, Safari and Opera have a neat implementation, but all other browsers are buggy. Some of them, don't even seem to support decimals (like BB10)!


Currently, Firefox honors the language of the HTML element in which the input resides. For example, try this fiddle in Firefox:

http://jsfiddle.net/ashraf_sabry_m/yzzhop75/1/

You will see that the numerals are in Arabic, and the comma is used as the decimal separator, which is the case with Arabic. This is because the BODY tag is given the attribute lang="ar-EG".

Next, try this one:

http://jsfiddle.net/ashraf_sabry_m/yzzhop75/2/

This one is displayed with a dot as the decimal separator because the input is wrapped in a DIV given the attribute lang="en-US".

So, a solution you may resort to is to wrap your numeric inputs with a container element that is set to use a culture that uses dots as the decimal separator.


use the pattern

<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."
>

good luck


As far as I understand it, the HTML5 input type="number always returns input.value as a string.

Apparently, input.valueAsNumber returns the current value as a floating point number. You could use this to return a value you want.

See http://diveintohtml5.info/forms.html#type-number


Use lang attribut on the input. Locale on my web app fr_FR, lang="en_EN" on the input number and i can use indifferently a comma or a dot. Firefox always display a dot, Chrome display a comma. But both separtor are valid.


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to google-chrome

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 SameSite warning Chrome 77 What's the net::ERR_HTTP2_PROTOCOL_ERROR about? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Jupyter Notebook not saving: '_xsrf' argument missing from post How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to make audio autoplay on chrome How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to decimal

Java and unlimited decimal places? What are the parameters for the number Pipe - Angular 2 Limit to 2 decimal places with a simple pipe C++ - Decimal to binary converting Using Math.round to round to one decimal place? String to decimal conversion: dot separation instead of comma Python: Remove division decimal Converting Decimal to Binary Java Check if decimal value is null Remove useless zero digits from decimals in PHP