Domanda

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..

È stato utile?

Soluzione 2

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

Altri suggerimenti

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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top