Truncating without Rounding a number using javascript or xsl?

Truncating without Rounding a number using javascript or xsl?

i shall pass the "number of digits to truncate".

examples:

number   digitsTruncate       Output

123.456        (3)              123.456
123.456        (2)              123.45
123.456789   (7)              123.4567890
123               (2)              123.00
123              (3)              123.000
123.4            (2)              123.40
123.4            (4)              123.4000



Thank you,

Regards
vh
vihar123Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ZvonkoSystems architectCommented:
Use toFixed() method of Number objects.
Like this:

<script>
alert((123.456).toFixed(3)+
"\n"+(123.456).toFixed(2)+
"\n"+(123.456789).toFixed(7)+
"\n"+(123).toFixed(2)+
"\n"+(123).toFixed(3)+
"\n"+(123.4).toFixed(2)+
"\n"+(123.4).toFixed(4));
</script>

BatalfCommented:
There could be simpler solution than this one, but it's a shot:

    <script type="text/javascript">

    function truncateNumber(inputNumber,digits){        
        var number = Math.floor(inputNumber);
        var decimal = (inputNumber - number) + "";        
        if(decimal.length>(digits+2))decimal = decimal.substr(0,(digits+2));
        var returnValue = (number + decimal)/1;        
        return returnValue.toFixed(digits);            
    }
   
    var number = 123.456 ;
    alert(truncateNumber(number,2));
   
    </script>

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BatalfCommented:
Zvonko,

I think toFixed() is rounding the number.

i.e.

    var number = 123.456;
    alert(number.toFixed(2));

yields 123.46 and not 123.45

Batalf
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

GwynforWebCommented:
toFixed() rounds (as said)

<script>
  function truncDigits(inputNumber,digits){
    fact= Math.pow(10,digits)    
    return Math.floor(inputNumber*fact)/fact
  }
   
  number = 123.456789
  alert(truncDigits(number,4))
  alert(truncDigits(number,3))
  alert(truncDigits(number,0))
</script>

ZvonkoSystems architectCommented:
That was also my first idea Gwyn, but then I tested with nums < 0.

Here my prototype:

<script>

Number.prototype.fixTo = fixToPlaces;

alert((123.456).fixTo(3)+
"\n"+(123.456).fixTo(2)+
"\n"+(123.456789).fixTo(7)+
"\n"+(123).fixTo(2)+
"\n"+(123).fixTo(3)+
"\n"+(123.4).fixTo(2)+
"\n"+(123.4).fixTo(4));



function fixToPlaces(p){
  for(var s="",i=0;i<p;i++) s+="0";
  var x = (this+'.').split('.')
  x = x[0]+((p>0)?"."+(x[1]+s).substr(0,p):"");
  return x;
}

</script>


ZvonkoSystems architectCommented:
Slightly better readable is this one:

<script>
Number.prototype.fixTo = fixToPlaces;

alert((123.456).fixTo(3)+
"\n"+(123.456).fixTo(2)+
"\n"+(123.456789).fixTo(7)+
"\n"+(123).fixTo(2)+
"\n"+(123).fixTo(3)+
"\n"+(123.4).fixTo(0)+
"\n"+(123.4).fixTo(2)+
"\n"+(123.4).fixTo(4));



function fixToPlaces(p){
  if(p<1) return parseInt(this);
  for(var s="",i=0;i<p;i++) s+="0";
  var x = (this+'.').split('.')
  x = x[0]+"."+(x[1]+s).substr(0,p);
  return x;
}

 

</script>

ZvonkoSystems architectCommented:
I hate to flooding this thread, but I had to remove the last line :)

function fixToPlaces(p){
  if(p<1) return parseInt(this);
  for(var s="",i=0;i<p;i++) s+="0";
  var x = (this+'.').split('.')
  return x[0]+"."+(x[1]+s).substr(0,p);
}


GwynforWebCommented:
My function works for -ve's as well in the sense that it cuts off the extra digits. which I believe is what is required here.
ZvonkoSystems architectCommented:
I used here your power factor for protopyping  :)

<script>
Number.prototype.toX = Number.prototype.toFixed;
Number.prototype.toFixed = fixNoRound;
function fixNoRound(p){
   var f = Math.pow(10,p);
   var n = Math.floor(this*f)/f;
   return n.toX(p);
}

alert((123.456).toFixed(3)+
"\n"+(123.456).toFixed(2)+
"\n"+(123.456789).toFixed(7)+
"\n"+(123).toFixed(0)+
"\n"+(0.01).toFixed(5)+
"\n"+(123).toFixed(3)+
"\n"+(123.4).toFixed(2)+
"\n"+(123.4).toFixed(4));
</script>

GwynforWebCommented:
?
ZvonkoSystems architectCommented:
Sorry, I misspelled the word prototyping.
It shoild read: "I used here your power factor for prototyping."
AnarchonCommented:
Ah, the just of type interconversion...this version leaves you with a string. That has the sole virtue of conserving trailing zeroes, if you intend to maintain the significance of such.

---
<html>

<head>
   <script>
      function truncateToDecimalPlace(amt, dec) {
      // Return string, containing amount >amt< truncated to >dec< decimal places.
         if (dec < 0) return 'bad call to truncateToDecimalPlace(): dec = ' + dec;
         var str = '' + amt;  // Force conversion to string type, if numeric.
         if (-1 == str.indexOf('.')) str += '.';
         str += '0000000000';  // should handle reasonable cases
         return str.slice(0, str.indexOf('.') + dec + (dec == 0 ? 0 : 1));
      }
alert('fmtToDecimalPlace(123.15678, 4) is >' + truncateToDecimalPlace(123.15678, 4) + '<');
alert('fmtToDecimalPlace(123.15678, 2) is > ' + truncateToDecimalPlace(123.15678, 2) + '<');
alert('fmtToDecimalPlace(123.9, 0) is > ' + truncateToDecimalPlace(123.9, 0) + '<');
   </script>
</head>

<body>
</body>

</html>
NiversoftCommented:
Why not using parseInt() ?

var value = 123.45;
value = parseInt(value);
alert(value);
NiversoftCommented:
ah, never mind.
heartland-techCommented:
The accepted solution is incorrect.
Here is the correction to the accepted solution:

    function truncateNumber(inputNumber, digits){        
        var number = Math.floor(inputNumber);
        var fdecimal = (inputNumber - number) + '';
        if(fdecimal.length > (digits + 2))
            fdecimal = fdecimal.substr(0, (digits + 2));
        var returnValue = (number/1 + fdecimal/1);
        return returnValue.toFixed(digits);            
    }

function truncateNumber(inputNumber, digits){        
        var number = Math.floor(inputNumber);
        var fdecimal = (inputNumber - number) + '';
        if(fdecimal.length > (digits + 2)) 
            fdecimal = fdecimal.substr(0, (digits + 2));
        var returnValue = (number/1 + fdecimal/1);        
        return returnValue.toFixed(digits);            
    }

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.