0

i have a little question: how i can limit or generate the result of a query in 7 or 8 digits

example:

var x = 3143284294
var y = 387520525892
var z = -7632489234892
var w = 34563

result:

var x = 3143284
var y = 3875205
var z = -763248
var w = 3456300 (fill whit "0")

What function or prefix in javascript will use?

tnks(and sorry for my english)

2 Answers2

2

This converts the number to a string and performs string operations on it. Note that repeat is a fairly recent feature of ECMAScript.

function cutNum(n, limit) {
    n = n + '';
    n = n.substr(0, limit);
    if (n.length < limit) {
        n = n + '0'.repeat(limit - n.length);
    }
    return parseInt(n, 10);
}

var x = 3143284294;
cutNum(x, 7); // 3143284

var z = -7632489234892;
cutNum(z, 7); // -763248

var w = 34563;
cutNum(w, 7); // 3456300
0

Take a look at the slice() method.

 var numbers = "01234567890";
 var res = numbers.slice(0,6);
 alert(res);

Since your sample also includes that are less than 7 digits, you will want to run a logic check first prior to the slice.

var x = "01" 

if(x.length < 7)
  x = x + "0000000";
x = x.slice(0,6);
alert(x);
Ans.
  • 11
  • 1