Force decimal point instead of comma in HTML5 number input (client-side)
Asked Answered
G

17

134

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

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/

Graces answered 30/5, 2011 at 15:50 Comment(7)
Have you found a solution yet? I am experiencing almost the same problem on Chrome 11 on Windows.Bant
No solution yet. Best guess is to avoid this (and use input type="text") untill this is fixed...Graces
Looks like is dependent of the locales of your browser, in my chrome I see comma, in my partner's chrome I see dot.Spent
See also here: https://mcmap.net/q/159841/-new-webkits-convert-decimal-comma-to-dot-and-vice-versa-in-number-type-inputs-javascript-name-of-that-browser-featurePyrotechnic
As i have also recently found out, some countries use comma instead of a 'decimal point.Rutheruthenia
That's exactly the point! Client locale settings force comma in countries where they use comma. I'm living in such a country and now wish to use the input with a decimal point.Graces
@Rutheruthenia yes we do, but some of us try not to. what is annoying is that the people who set these 'standards' assume this is how some countries do itNne
A
45

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

Antipope answered 30/9, 2011 at 12:2 Comment(5)
This still doesn't work :-( Client-side local values always transform the decimal point in a decimal comma, regardless of step, or value attribute. :-(Graces
As I understand the question is not about having a decimal separator. The question is about having '.' instead of ',' when the locale of the client prefers ','.Velvety
no matter what decimal separator you use in the step attribute - the browser will still localise it. That is, with your example given - in most European countries the number displayed would be 10,56Rhetic
I came back and re-read the question 5 years later and wondered why I provided the answer above. See the edit, pleaseAntipope
It will also not work if the data is being saved using ajax.Doble
U
34

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.

Unhealthy answered 22/3, 2015 at 11:21 Comment(10)
Interesting! Unfortunately it only seems to work in Firefox, not in Chrome (47.0.2526.106)Filberto
Even not in Firefox, in FranceDaff
1. Build a page fr-FR which contains a form en-US, try to enter a decimal number like 123.45 and bingo! input.value is empty. :-(Daff
Firefox respects the language setting of the page. Chrome imposes the decimal separator of the OS or the browser? Edge imposes the decimal point, regardless of the language settings of page or browser or OS. What a mess.Parsee
You don't need the wrapper element. You can set the lang attribute directly on the input element.Searching
there is no any effect define lang or not. Please define es-ES and see resultBaumbaugh
@NuriYILMAZ What browser are testing on? It still doesn't work on ChromeUnhealthy
The lang attribute actually made the difference for me, thanks!Distance
The first link does not use the lang attributeGable
@LeonardoSibela It does. Click on the HTML menu in the top left of the HTML editing part of the fiddle, a drop down menu will open that has the definition of the BODY tagUnhealthy
L
18

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

<input type="number" step="any">
Laurence answered 12/7, 2013 at 21:32 Comment(0)
L
7

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.

Lavolta answered 23/11, 2017 at 7:49 Comment(0)
N
6

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.

Nonaggression answered 10/12, 2012 at 7:3 Comment(3)
In that case it's a good thing I wrote a summary and then extrapolated, eh?Nonaggression
In my case GeolocationPosition.coords.latitude sometimes returns a float like 99.999999999999999. So the input step will be: step="0.000000000000001" to be a valid required inputSenseless
@Senseless By the 5th decimal point, you get to 1 meter accuracy, 6th decimal point is 10cm accuracy. Anything after that (dependent on your situation) is unnecessary.Knossos
C
6

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)!

Cathepsin answered 23/7, 2013 at 15:31 Comment(1)
Using a library like number.js might help with the inherent problems of having multiple languages on this planet.Nadene
E
6

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.

Espagnole answered 17/3, 2015 at 9:7 Comment(3)
Hi Andrea, is there any way to do this without Angular JS? With jQuery for example?Graces
Sure, I suppose you could write, on a per-number-input basis, something like $("input[type=number]").on("keydown", function(e) { if(e.keyCode === 188) { this.value += "."; e.preventDefault(); }}); (once your page has fully loaded along with all the number inputs)Espagnole
This snippet doesn't work on chrome (tested with v60). When typing 888,, setting the value property throws a warning stating that 888. is not a valid number (the regexp requires at least one number after the dot) and blanks the field. Typing a dot works though, probably because the input consider its value “in progress” and waits for more digits to be typedBoleyn
P
2

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

Packthread answered 30/5, 2011 at 16:5 Comment(0)
W
1

Have you considered using Javascript for this?

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

Wyandotte answered 10/12, 2014 at 13:7 Comment(1)
On chrome with input[type = number] is not working.. comma is always shown.Pyrotechnic
T
1

The below is a work arround to enable the input of a comma and replace it by a dod. It works very well for continious input of the user.

The idea is to have an input that can be parsed into a number "123." cannot be parsed, but "123.0" can be parsed, and so the type of the input can be changed back from "text" to "number" and it still works. The selection is "just" to enable continious input, so the user overwrites the additional number

HTML element:

<input type="number" id="numberinput">

Javascript


document.getElementById("numberinput").keydown = function(event)
{
    if (
        event.target.getAttribute('type') === "number" &&
        event.key === "," &&
        event.target.value.indexOf(".") === -1)
    {
        event.preventDefault();
        event.target.setAttribute("type","text");
        event.target.value = event.target.value + ".0";
        event.target.setSelectionRange(event.target.value.length - 1, event.target.value.length);
        event.target.setAttribute("type","number");
    }
}
Torbert answered 1/4, 2022 at 21:54 Comment(0)
S
0

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

Superstitious answered 4/12, 2011 at 22:16 Comment(0)
A
0

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

Acidophil answered 10/12, 2014 at 14:4 Comment(1)
Actually, setting type as text is indeed nearly the only solution to make point stay point. In conjunction with pattern="\d+\.\d{2}" I'd even call such UX acceptable... I'd drop the jquery part, though...Hot
R
0

I have written a custom piece of code to do this

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

var input = document.querySelector('input[role="custom-number"]');
var bincr = document.querySelector('button[role="increment"]');
var bdecr = document.querySelector('button[role="decrement"]');

function translate_decimals(side = 0)
{
	input.value = (side == ',' ? input.value.replace('.',',') : input.value.replace(',','.'));
}
translate_decimals(',');

bincr.addEventListener('click', ()=>{
	if (input.hasAttribute('max'))
	{
		if (input.value.substr(0,input.getAttribute('max').length) == input.getAttribute('max').substr(0,input.getAttribute('max').length))
		{
			return;
		}
		else
		{
			translate_decimals('.');
			let temp = input.value;
			input.value = "";
			input.value = (input.hasAttribute('step') ? (parseFloat(temp) + parseFloat(input.getAttribute('step'))) : temp++);
			translate_decimals(',');
		}
	}
});

bdecr.addEventListener('click', ()=>{
	if (input.hasAttribute('min'))
	{
		if (input.value.substr(0,input.getAttribute('min').length) == input.getAttribute('min').substr(0,input.getAttribute('min').length))
		{
			return;
		}
		else
		{
			translate_decimals('.');
			input.value = (input.hasAttribute('step') ? (input.value - input.getAttribute('step')) : input.value--);
			translate_decimals(',');
		}
	}
});
/* styling increment & decrement buttons */
button[role="increment"],
button[role="decrement"] {
	width:32px;
}
<input type="text" role="custom-number" step="0.01" min="0" max="0" lang="en" value="1.99">
<button role="increment">+</button>
<button role="decrement">-</button>
Ringlet answered 10/2, 2020 at 0:22 Comment(0)
C
0

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);

  })

});
Concurrence answered 30/3, 2020 at 16:50 Comment(0)
O
-1

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

Otherness answered 26/11, 2017 at 1:52 Comment(1)
Hi, just tested it out in Chrome 62.0.3202.94 on Windows 10. It doesn't work. When using the spinner buttons, the input reverts to comma instead of point (considering Belgian locale settings). Thanks anyways.Graces
L
-2

Think u will need to set this globally in the Culture, so pick your local culture e.g. en-ZA, and it will set the time date, currency, etc all correct 4 all:)

Leatriceleave answered 24/1 at 12:12 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewArissa
G
-3

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.

Gooseneck answered 9/2, 2020 at 14:2 Comment(1)
But... but the question is about decimal numbers, step="3" would limit input to only whole numbers. And setting step="0.01" still shows it as a coma ;cHot

© 2022 - 2024 — McMap. All rights reserved.