0

I want to get specified format number.. help me plz..

I made function

    function ceilingAbsolute(inVal, pos){

        var digits = Math.pow(10, pos);

        var num = 0;

        var patten = "[0-9]{"+pos+"}$";
        var re = new RegExp(patten, "");

        num = inVal.replace(re);

        num = num * digits;

        return num;
}



var testVal = ceilingAbsolute(255555, 3) ;

I have expected testVal = 255000, but got "255undefined" ..

I want to get ceiling deciaml number..

somebody help please..

4

2 回答 2

6

The reason you're getting 255undefined is that you are not passing a replacement value to the replace function along with the regex. Why not just do:

function ceilingAbsolute(inVal, pos){
    var digits = Math.pow(10, pos);
    return parseInt(inVal / digits) * digits;
}
于 2013-05-08T01:25:16.967 回答
0

You can also do:

function absFloor(num, pos) {
  num += '';
  var len = num.length;
  if (pos < len) {
    return num.substring(0,len-pos) + ('' + Math.pow(10, pos)).substring(1);
  }
}

It can be reduced to two lines, but I think the test is important:

function absFloor(num, pos) {
  num += '';
  return num.substring(0,num.length-pos) + ('' + Math.pow(10, pos)).substring(1);
}
于 2013-05-08T01:47:11.103 回答