Javascript 如何在Javascript中.substr()一个整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3729492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:54:02  来源:igfitidea点击:

How to .substr() a integer in Javascript

javascript

提问by Allen Gingrich

As the title says, which function will give me a result similar to what .substr() does, only for integers?

正如标题所说,哪个函数会给我类似于 .substr() 所做的结果,仅适用于整数?

Thanks!

谢谢!

UPDATE:

更新:

Here is what isn't working:

这是不起作用的:

if ($(#itemname).val() == "Not Listed") {

        var randVal = Math.random() * 10238946;

        var newVal = randVal.toString().substr(0, 4);

        $("#js_itemid").val(randVal);

        $("#js_price").val("199.99");

    }

回答by svanryckeghem

What about ...

关于什么 ...

var integer = 1234567;
var subStr = integer.toString().substr(0, 1);

... ?

……?

回答by vol7ron

Given

给定的

var a = 234; 

There are several methods to convert a number to a string in order to retrieve the substring:

有几种方法可以将数字转换为字符串以检索子字符串:

  • string concatenation
  • Number.prototype.toString() method
  • template strings
  • String object
  • 字符串连接
  • Number.prototype.toString() 方法
  • 模板字符串
  • 字符串对象


Examples

例子

Included are examples of how the given number, a, may be converted/coerced.

包括如何a转换/强制给定数字的示例。

Empty string concatenation

空字符串连接

(a+'').substr(1,1);        // "3"

Number.prototype.toString method

Number.prototype.toString 方法

a.toString().substr(1,1)   // "3"

Template strings

模板字符串

`${a}`.substr(1,1)         // "3"

String object

字符串对象

String(a).substr(1,1)      // "3"

回答by STW

Would converting to a string first be ok?

首先转换为字符串可以吗?

var x = 12345;
var xSub = x.toString().substr(1,3);

alert(xSub);? // alerts "234"

回答by Gabriele Petrioli

You should convert it to string first with toString()

您应该先将其转换为字符串 toString()

var a = 105;

alert(a.toString().substr(1,2));

回答by Leandro Rodrigues Combinato

You might want to try this:

你可能想试试这个:

<script>
var x = '146870';

    function format(num){
        return (num / 100).toFixed(2);
    }

    alert(format(x));
</script>