在Javascript中删除数字中的前导零 [英] Remove leading zeros from a number in Javascript

查看:117
本文介绍了在Javascript中删除数字中的前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:


什么是最简单和跨浏览器兼容的方法,可以从Javascript中的数字中删除前导零?



例如如果我将文本框的值设置为014或065,则它应该只返回14或65 试试 parseInt

  parseInt(065,10); 



第二个参数用于 radix ,并根据文档应始终指定。 MDN表示,


radix


一个整数代表上述
字符串的基数。始终指定此参数以消除读者混淆
并保证可预测的行为。当不指定基数时,不同的实现
会产生不同的结果。

.............

....... ......

如果基数未定义或0(或缺失),JavaScript假定如下:


  • 如果输入字符串以0x或0X开头,则基数为16
    (十六进制),并且解析字符串的其余部分。

  • 如果输入的字符串以0开头,则基数为八(八进制)或十(十进制)。
    究竟选择哪个基数是依赖于实现的。 ECMAScript
    5指定使用10(十进制),但并非所有浏览器都支持
    。出于这个原因在使用parseInt 时总是指定一个基数。
  • 如果输入字符串以任何其他值开头,则基数为10
    (十进制)。
    例如,在某些实现中, parseInt(01803)将产生<



    C $ C> 1 。假设目标是获得 1803 ,请以10为基数调用parseInt以确保解析在基本的十进制编号系统中完成。即: parseInt(01803,10)会产生 1803 。请注意,对于非整数值,parseInt()将四舍五入数字作为整数返回。 paseInt(018.03,10)会产生 18


    Possible Duplicate:
    Truncate leading zeros of a string in Javascript

    What is the simplest and cross-browser compatible way to remove leading zeros from a number in Javascript ?

    e.g. If I have a textbox value as 014 or 065, it should only return 14 or 65

    解决方案

    Try parseInt.

    parseInt("065", 10);
    


    The second parameter is for the radix and as per the documentation it should always be specified. MDN says,

    radix

    An integer that represents the radix of the above mentioned string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
    .............
    .............
    If radix is undefined or 0 (or absent), JavaScript assumes the following:

    • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
    • If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
    • If the input string begins with any other value, the radix is 10 (decimal).

    For example, in some implementations parseInt("01803") will yield 1. Assuming the goal is to get 1803, call parseInt with a radix of 10 to ensure the parsing is done in a base decimal numbering system. That is: parseInt("01803", 10) will yield 1803. Please note that for a non-integer value, parseInt() will round the number to return as an integer. paseInt("018.03", 10) will yield 18.

    这篇关于在Javascript中删除数字中的前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆