Truncating Numbers in JavaScript

By | May 29, 2016
I needed a function to truncate a number. Math.floor() worked … until I tried it on a negative number.

So I had to write my own truncate function. Even though I needed to truncate numbers to the integer portion only, I figured sooner or later I would need to truncate to a given number of decimal places. This function does that.

<script>// <![CDATA[
function ccTruncate(number, places) {
    var shift = Math.pow(10, places);
    return ((number * shift) | 0) / shift;
// ]]></script>

If you find this useful, let me know in the comments below.

Leave a Reply