Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to .substr() a integer in Javascript

Tags:

javascript

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

    }
like image 495
Allen Gingrich Avatar asked Sep 16 '10 18:09

Allen Gingrich


People also ask

Can you substring an int in Java?

substring(int beginIndex, int endIndex) method returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

What does substring () do in JavaScript?

The substring() method returns the part of the string between the start and end indexes, or to the end of the string.

How do I cut a number in JavaScript?

Trunc() method. The Math. trunc() is the most popular method to remove the decimal part of JavaScript. It takes positive, negative, or float numbers as an input and returns the integer part after removing the decimal part.

What substring () and substr () will do?

The substr() method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters. The substring() method returns the part of the string between the start and end indexes, or to the end of the string.


2 Answers

What about ...

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

... ?

like image 77
svanryckeghem Avatar answered Sep 27 '22 19:09

svanryckeghem


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"
like image 38
vol7ron Avatar answered Sep 27 '22 17:09

vol7ron