152

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

devha
  • 3,307
  • 4
  • 28
  • 52
  • My guess is the root cause of some of your problems is that the browsers are set to a US locale which uses the dot as a decimal separator. It seems like Chrome and Android are getting confused by this in different ways - Chrome treats the comma as a digit separator, then converts the input to a number, then converts it to a string again for `.val()`, and Android does something weird. Can you check if they behave the same when you set the system language to something appropriate? – millimoose Mar 08 '13 at 22:03
  • 1
    Nvm posted this as an answer – kjetilh Mar 08 '13 at 22:06
  • See also here: http://stackoverflow.com/a/24423879/196210 – Revious Dec 03 '14 at 15:15
  • The situation is even worse than you depicted: you get a decimal point or comma on the WP numpad depending on the language you chose your keyboard to work on. There is also no way to find out which was the input locale (not necessarily the preferred browser language)... So the best I could come up with (and what is good enough for me) is: ```var number = $(...).get(0).valueAsNumber;``` ```if (isNaN(number)) number = parseFloat($(...).val().replace(',', '.');``` But that solution only works if the number that has been put in only contains 1 comma and no extra dots... – bert bruynooghe Feb 04 '15 at 19:55

10 Answers10

122

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.

BairDev
  • 2,865
  • 4
  • 27
  • 50
natchiketa
  • 5,867
  • 2
  • 28
  • 25
  • 10
    If you want to allow arbitrarily many decimal places, specify the `step` attribute as `"any"` instead of e.g. `"0.01"` as shown here. See [this tweaked version](http://jsfiddle.net/xrujZ/126/) of nathciketa's fiddle for a demo. – Mark Amery Feb 18 '14 at 15:27
  • 4
    I also ran into issues with commas not validating, though I was entering "1,234.56" into ``. I haven't been able to find a way to turn HTML5 validation off. I can turn off or customize the error message, but retrieving the value from the input is always a crapshoot. Any ideas? – Nick G. Sep 10 '14 at 22:20
  • 6
    `This attribute applies when the value of the type attribute is text, search, tel, url, email, or password, otherwise it is ignored.` So pattern is useless with `type="number"` – Michael Laffargue Jul 27 '17 at 13:22
  • like michael said, please change the `type` to `text`, otherwise your answer does make no sense. – phil294 Oct 20 '17 at 22:20
28

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."/>
kjetilh
  • 4,821
  • 2
  • 18
  • 24
  • 2
    **input.valueAsNumber** - No help as this works only with dots as decimal separator and in my case enduser might use dot or comma. **Form tag novalidate** - Have not found any affect on this. – devha Mar 09 '13 at 07:44
  • Unfortunately I'm running out of ideas, so I'm not sure if you're able to make this work cross-browser without a workaround solution. I've updated my answer to include the *pattern* attribute I also found one can use the *formnovalidate* attribute directly on the input fields. I know you won't like it but if everything fails and you absolutely need commas then **input="text"** might be the only way.. – kjetilh Mar 09 '13 at 08:31
  • It looks like input type number generates more issues than actually improves user experience. In mobile device it would be great if I can open only numeric keyboard to user if I want them to input just numbers. Anyway I need to re-think this once again... – devha Mar 09 '13 at 14:08
  • Because we also need to support using both dot and comma as decimal separator, we plan to use pattern for validation on desktop in combination with type="text". Then we will add feature detection for detecting mobile device and use type="number" when that applies. – awe Nov 17 '14 at 08:47
  • What worked out for me is to amend the input type temporarily to a text, add the ".0" and then change it back to a "number" type. https://stackoverflow.com/a/71713100/3559690 – hsc Apr 01 '22 at 22:02
10

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.

Daniel
  • 4,525
  • 3
  • 38
  • 52
9

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

David Navarro
  • 91
  • 1
  • 1
  • But it is not compatible with all browsers, only with latest versions of iOS Safari, Chrome, Chromium, Opera... https://caniuse.com/#feat=input-inputmode :( – pgarciacamou Jun 27 '19 at 21:39
  • And additionally you don't get this neat number keyboard on mobile devices. – ˈvɔlə Sep 08 '19 at 15:00
7

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.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
4

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.

Bolo
  • 1,494
  • 1
  • 19
  • 19
1

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
  • Does not work. Try parseFloat("1,5") in IE11. Returns 1. Language is German for both OS and IE. – T3rm1 Nov 18 '16 at 12:25
1

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

var currentString = '';
var badState = false;
var lastCharacter = null;

document.getElementById("field").addEventListener("keyup",($event) => {
  if ($event.target.value && !$event.target.validity.badInput) {
          currentString = $event.target.value;
  } else if ($event.target.validity.badInput) {
    if (badState && lastCharacter && lastCharacter.match(/[\.,]/) && !isNaN(+$event.key)) {
      $event.target.value = ((+currentString) + (+$event.key / 10));
      badState = false;
    } else {
      badState = true;
    }
  }
  document.getElementById("number").textContent = $event.target.value;
  lastCharacter = $event.key;
});

document.getElementById("field").addEventListener("blur",($event) => {
 if (badState) {
    $event.target.value = (+currentString);
    badState = false;
  document.getElementById("number").textContent = $event.target.value;
  }
});
#result{
  padding: 10px;
  background-color: orange;
  font-size: 25px;
  width: 400px;
  margin-top: 10px;
  display: inline-block;
}

#field{
  padding: 5px;
  border-radius: 5px;
  border: 1px solid grey;
  width: 400px;
}
<input type="number" id="field" keyup="keyUpFunction" step="0.01" placeholder="Field for both comma separators">

<span id="result" >
 <span >Current value: </span>
 <span id="number"></span>
</span>

Angular 9 Snippet

@Directive({
  selector: '[appFloatHelper]'
})
export class FloatHelperDirective {
  private currentString = '';
  private badState = false;
  private lastCharacter: string = null;

  @HostListener("blur", ['$event']) onBlur(event) {
    if (this.badState) {
      this.model.update.emit((+this.currentString));
      this.badState = false;
    }
  }

  constructor(private renderer: Renderer2, private el: ElementRef, private change: ChangeDetectorRef, private zone: NgZone, private model: NgModel) {
    this.renderer.listen(this.el.nativeElement, 'keyup', (e: KeyboardEvent) => {
      if (el.nativeElement.value && !el.nativeElement.validity.badInput) {
        this.currentString = el.nativeElement.value;
      } else if (el.nativeElement.validity.badInput) {
        if (this.badState && this.lastCharacter && this.lastCharacter.match(/[\.,]/) && !isNaN(+e.key)) {
          model.update.emit((+this.currentString) + (+e.key / 10));
          el.nativeElement.value = (+this.currentString) + (+e.key / 10);
          this.badState = false;
        } else {
          this.badState = true;
        }
      }       
      this.lastCharacter = e.key;
    });
  }
  
}
<input type="number" matInput placeholder="Field for both comma separators" appFloatHelper [(ngModel)]="numberModel">
Joniras
  • 1,258
  • 10
  • 32
0

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.

Patrick D'appollonio
  • 2,722
  • 1
  • 18
  • 34
0

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

Community
  • 1
  • 1
stackasec
  • 65
  • 5
  • 2
    It is usual to give more explanation of the solution even if the answer if fully covered by linked content. – IvanH May 30 '13 at 09:39
  • This approach seems to be better than the other approaches if the back end server is determining the locale rather than the browser itself. Unfortunately, ```toLocaleString``` is not reliable across platforms. – bert bruynooghe Feb 04 '15 at 08:54
  • Cross platform support seems wide enough to me in 2015, see e.g. [Mozillas Devnet](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_Compatibility). However, if it still is of concern for you, [find possible solutions in here.](http://stackoverflow.com/questions/16157762/tolocalestring-not-supported-in-all-browsers) – stackasec Feb 05 '15 at 10:05
  • Mozillas Devnet shows almost no compatiblilty for mobile browsers, and that's exactly where numeric textfield can offer most benefits. (See original question.) – bert bruynooghe Feb 06 '15 at 20:52
  • ... and more than enough alternatives have been shown and referenced. Have fun. – stackasec Feb 07 '15 at 21:17