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
|
5 Answers
Reset to default 31What 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>
newVal
is never used, you storerandVal
in the js_itemid – vol7ron Commented Sep 16, 2010 at 18:23