最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to .substr() a integer in Javascript - Stack Overflow

programmeradmin1浏览0评论

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

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

    }

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

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

    }
Share Improve this question edited Sep 16, 2010 at 18:20 Allen Gingrich asked Sep 16, 2010 at 18:14 Allen GingrichAllen Gingrich 5,65711 gold badges46 silver badges57 bronze badges 5
  • 3 Can you give an example of an input and expected output? – Gumbo Commented Sep 16, 2010 at 18:15
  • See update in OP for my example of what I'm using it for. Converting it to a string does not work for some reason... – Allen Gingrich Commented Sep 16, 2010 at 18:21
  • And what did you expect to happen? – Gumbo Commented Sep 16, 2010 at 18:23
  • 2 what's the error? note: your newVal is never used, you store randVal in the js_itemid – vol7ron Commented Sep 16, 2010 at 18:23
  • There was an error unrelated to this issue. :( Too many answers to delete, but thank you all! It is solved. – Allen Gingrich Commented Sep 16, 2010 at 18:26
Add a comment  | 

5 Answers 5

Reset to default 31

What about ...

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

... ?

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

Examples

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

Empty string concatenation

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

Number.prototype.toString method

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

Template strings

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

String object

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

Would converting to a string first be ok?

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

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

You should convert it to string first with toString()

var a = 105;

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

You might want to try this:

<script>
var x = '146870';

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

    alert(format(x));
</script>
发布评论

评论列表(0)

  1. 暂无评论