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

后端 未结 10 603
情话喂你
情话喂你 2020-11-27 11:15

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 exper

相关标签:
10条回答
  • 2020-11-27 11:44

    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.

    0 讨论(0)
  • 2020-11-27 11:47

    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
    
    0 讨论(0)
  • 2020-11-27 11:47

    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

    0 讨论(0)
  • 2020-11-27 11:50

    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.

    0 讨论(0)
提交回复
热议问题