129

I am trying to truncate decimal numbers to decimal places. Something like this:

5.467   -> 5.46  
985.943 -> 985.94

toFixed(2) does just about the right thing but it rounds off the value. I don't need the value rounded off. Hope this is possible in javascript.

Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
kcssm
  • 1,727
  • 3
  • 16
  • 19
  • 7
    jQuery is just a framework and your problem is not jQuery related. It is more about doing some basic computation in JavaScript. I hope you are also satisfied with a non-jQuery solution. – Felix Kling Feb 06 '11 at 10:50
  • I found it to be too much work to get my calculations to return just 2 decimals using Javascript. I was able to do it easily in my database view instead. I realize that this method won't fit every situation, but I want to put it out here because it might save somebody a lot of time. – MsTapp Nov 01 '16 at 13:06

32 Answers32

78

Dogbert's answer is good, but if your code might have to deal with negative numbers, Math.floor by itself may give unexpected results.

E.g. Math.floor(4.3) = 4, but Math.floor(-4.3) = -5

Use a helper function like this one instead to get consistent results:

truncateDecimals = function (number) {
    return Math[number < 0 ? 'ceil' : 'floor'](number);
};

// Applied to Dogbert's answer:
var a = 5.467;
var truncated = truncateDecimals(a * 100) / 100; // = 5.46

Here's a more convenient version of this function:

truncateDecimals = function (number, digits) {
    var multiplier = Math.pow(10, digits),
        adjustedNum = number * multiplier,
        truncatedNum = Math[adjustedNum < 0 ? 'ceil' : 'floor'](adjustedNum);

    return truncatedNum / multiplier;
};

// Usage:
var a = 5.467;
var truncated = truncateDecimals(a, 2); // = 5.46

// Negative digits:
var b = 4235.24;
var truncated = truncateDecimals(b, -2); // = 4200

If that isn't desired behaviour, insert a call to Math.abs on the first line:

var multiplier = Math.pow(10, Math.abs(digits)),

EDIT: shendz correctly points out that using this solution with a = 17.56 will incorrectly produce 17.55. For more about why this happens, read What Every Computer Scientist Should Know About Floating-Point Arithmetic. Unfortunately, writing a solution that eliminates all sources of floating-point error is pretty tricky with javascript. In another language you'd use integers or maybe a Decimal type, but with javascript...

This solution should be 100% accurate, but it will also be slower:

function truncateDecimals (num, digits) {
    var numS = num.toString(),
        decPos = numS.indexOf('.'),
        substrLength = decPos == -1 ? numS.length : 1 + decPos + digits,
        trimmedResult = numS.substr(0, substrLength),
        finalResult = isNaN(trimmedResult) ? 0 : trimmedResult;

    return parseFloat(finalResult);
}

For those who need speed but also want to avoid floating-point errors, try something like BigDecimal.js. You can find other javascript BigDecimal libraries in this SO question: "Is there a good Javascript BigDecimal library?" and here's a good blog post about math libraries for Javascript

Community
  • 1
  • 1
Nick Knowlson
  • 7,185
  • 6
  • 47
  • 63
  • Why unexpected? Changing the direction of rounding when you go below 0, causes all sorts of arithmetical artefacts & crappy math. For example, twice as many numbers will round to 0, as any other integer. For graphics, accounting & many other uses, you'll get crappy results. To tell you the truth, it'd be harder to say what your suggestion is *good* for as to say what it's *not*. – Thomas W Jun 14 '12 at 01:54
  • It's good for exactly what it says - when you want to truncate decimals rather than rounding. – Nick Knowlson Jun 14 '12 at 15:32
  • 1
    Not going to work with 17.56 because browser gives 17.56 * 100 = 1755.9999999999998 not 1756 – shendz Feb 12 '13 at 20:30
  • Good point shendz. I've updated my answer with a solution that eliminates all floating-point error for those who need that. – Nick Knowlson Mar 01 '13 at 21:50
  • 1
    This won't work for numbers that are less than 1 if you want no decimals - truncateDecimals(.12345, 0) results in NaN unless you add a check: `if(isNAN(result) result = 0;` Depends on the behavior you want. – Jeremy Witmer Apr 22 '13 at 22:18
  • I didn't know what you were talking about at first, until I realized that ".1".toString doesn't always return "0.1", maybe only in Firefox's developer tools. I'll fix it, thanks. – Nick Knowlson Apr 23 '13 at 00:33
  • if(isNan( is missing a closing bracket – lukas.pukenis Oct 09 '13 at 10:49
  • +1. This does not handle integers (with no decimal point in them). Checking for `decPos` to be -1 will fix it. Like this: `result = decPos === -1 ? num : numS.substr(0, 1 + decPos + digits);` – Hari Pachuveetil Feb 04 '14 at 05:29
  • Aha, so it doesn't. Small integers end up working fine, that's probably why I didn't notice back when I first wrote it. Fixed now, thanks! – Nick Knowlson Feb 18 '14 at 18:15
60

upd:

So, after all it turned out, rounding bugs will always haunt you, no matter how hard you try to compensate them. Hence the problem should be attacked by representing numbers exactly in decimal notation.

Number.prototype.toFixedDown = function(digits) {
    var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
        m = this.toString().match(re);
    return m ? parseFloat(m[1]) : this.valueOf();
};

[   5.467.toFixedDown(2),
    985.943.toFixedDown(2),
    17.56.toFixedDown(2),
    (0).toFixedDown(1),
    1.11.toFixedDown(1) + 22];

// [5.46, 985.94, 17.56, 0, 23.1]

Old error-prone solution based on compilation of others':

Number.prototype.toFixedDown = function(digits) {
  var n = this - Math.pow(10, -digits)/2;
  n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
  return n.toFixed(digits);
}
kirilloid
  • 14,011
  • 6
  • 38
  • 52
  • 4
    Yeah, Prototypes don't work reliably cross-browser. Instead of defining this (limited purpose) function through the type system, in a way that doesn't work reliably, why not just put it in a library. – Thomas W Jun 14 '12 at 01:47
  • 3
    This does not work as excepted. Try the number 17.56 and digits = 2. It should be 17.56, but this function returns 17.55. – shendz Feb 12 '13 at 20:29
  • Thanks for report, this is an important notice. Unfortunately `17.56 != 17.55 - 0.01`. I updated the code. – kirilloid Feb 13 '13 at 14:30
  • 2
    Two inconsistencies with this function: This function returns a string so `1.11.toFixedDown(1) + 22` ends up as `1.122` instead of `23.1`. Also `0.toFixedDown(1)` should produce `0` but instead it produces `-0.1`. – Nick Knowlson Mar 11 '14 at 22:41
  • 5
    Note that this function removes the negative sign. Ex: `(-10.2131).toFixedDown(2) // ==> 10.21`. – rgajrawala Jul 15 '14 at 16:20
  • 4
    Also, `(1e-7).toFixedDown(0) // ==> 1e-7`. Does that for `1e-(>=7)` (ex: `1e-8`, `1e-9`, ...). – rgajrawala Jul 15 '14 at 16:38
  • This is solution is good enough in my case, I only changed the regExp a little: "(-*\\d+\\.\\d{" + digits + "})(\\d)" – Alex Pi Jan 13 '15 at 18:39
  • 1
    I'd write `"([-+]?\\d+\\.\\d{" + digits + "})(\\d)"` then. – kirilloid Jan 14 '15 at 12:57
  • This answer is obsurd. You shouldn't be editting the javascript Number class to remove decimal points. It complicates the issue a lot more than it has to be. – jStaff Sep 28 '18 at 17:30
  • It seems that function works correctly but author's statement: "rounding bugs will always haunt you" is incorrect. There are also correct and more simple (and fast) solutions are provided in some other answers here. – Konstantin Smolyanin May 13 '19 at 11:38
  • I'd write "([-+]?\\d*\\.\\d{" + digits + "})(\\d)" => Ex: .00 , .00009, .999999 – Esteban Sep 26 '19 at 19:12
40
var a = 5.467;
var truncated = Math.floor(a * 100) / 100; // = 5.46
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • 5
    This works well but will give results that are probably undesirable if he (or someone else looking at this answer later) has to deal with negative numbers. See http://stackoverflow.com/a/9232092/224354 – Nick Knowlson Feb 10 '12 at 17:31
  • 3
    Why undesirable? Changing the direction of rounding when you go below 0, causes all sorts of arithmetical artefacts. – Thomas W Jun 14 '12 at 01:50
  • 9
    There is a difference between rounding and truncating. Truncating is clearly the behaviour this question is seeking. If I call `truncate(-3.14)` and receive `-4` back, I would definitely call that undesirable. – Nick Knowlson Aug 13 '13 at 21:34
  • I agree with Thomas. The difference in perspective may come with whether you are usually truncating for display, or for computation. From a computational perspective, this avoids "arithmetical artifacts" –  Jun 09 '15 at 17:25
  • 3
    `var a = 65.1` `var truncated = Math.floor(a * 100) / 100; // = 65.09` Hence this is not a correct solution – Sanyam Jain Dec 28 '17 at 08:44
21

Nice one-line solution:

function truncate (num, places) {
  return Math.trunc(num * Math.pow(10, places)) / Math.pow(10, places);
}

Then call it with:

truncate(3.5636232, 2); // returns 3.56
truncate(5.4332312, 3); // returns 5.433
truncate(25.463214, 4); // returns 25.4632
MeestorHok
  • 240
  • 2
  • 7
  • 2
    I like this solution, but just keep in mind that it's not fully supported by all browsers. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Browser_compatibility) – Gene Parcellano Jan 19 '17 at 19:10
  • Would love if that worked 100%, but Math.trunc(0.29 * Math.pow(10, 2)) / Math.pow(10, 2) gives you 0.28. To be honest the only reliable way I've seen so far is by splitting/cutting strings. – HelpfulPanda Dec 15 '20 at 12:05
  • @HelpfulPanda pff yeah, wtf :| I'm currently having hard times solving this issue, so I think I'll fallback as you proposed to strings :) – stackoverflow Mar 21 '22 at 07:42
21

You can fix the rounding by subtracting 0.5 for toFixed, e.g.

(f - 0.005).toFixed(2)
RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262
  • 1
    Heads up: as it is this doesn't work for very small numbers, numbers with more than 3 decimal places, or negative numbers. Try .0045, 5.4678 and -5.467 – Nick Knowlson Oct 23 '13 at 21:47
  • This will work so long as you match the value you are subtracting with the length you wish to have. whatever you pass to toFixed() needs to be the number of 0's after the decimal. – dmarra Apr 02 '18 at 19:34
19

Consider taking advantage of the double tilde: ~~.

Take in the number. Multiply by significant digits after the decimal so that you can truncate to zero places with ~~. Divide that multiplier back out. Profit.

function truncator(numToTruncate, intDecimalPlaces) {    
    var numPower = Math.pow(10, intDecimalPlaces); // "numPowerConverter" might be better
    return ~~(numToTruncate * numPower)/numPower;
}

I'm trying to resist wrapping the ~~ call in parens; order of operations should make that work correctly, I believe.

alert(truncator(5.1231231, 1)); // is 5.1

alert(truncator(-5.73, 1)); // is -5.7

alert(truncator(-5.73, 0)); // is -5

JSFiddle link.

EDIT: Looking back over, I've unintentionally also handled cases to round off left of the decimal as well.

alert(truncator(4343.123, -2)); // gives 4300.

The logic's a little wacky looking for that usage, and may benefit from a quick refactor. But it still works. Better lucky than good.

Community
  • 1
  • 1
ruffin
  • 16,507
  • 9
  • 88
  • 138
  • This is the best answer. If you extend the `Math` prototype with this and check for NaN-s before executing, it would be just perfect. – Liglo App Dec 03 '14 at 15:59
  • `truncator((10 * 2.9) / 100, 2)` return 0.28 instead of 0.29 ... https://jsfiddle.net/25tgrzq1/ – Alex Jun 29 '19 at 18:10
  • Not working for me, truncator(1000.12345678, 7) returns 141.1299975 – HelpfulPanda Dec 15 '20 at 11:52
  • @Alex If you want to avoid floating point errors, [use a decimal type](https://stackoverflow.com/a/3439981/1028230). Or I guess we could rewrite to use string manipulation, but that seems insane. You'll notice [similar answers](https://stackoverflow.com/a/22468007/1028230) have the same issue. – ruffin Dec 15 '20 at 21:38
  • @HelpfulPanda That's because [JavaScript uses 32-bit ints for bitwise operators](https://stackoverflow.com/a/2373863/1028230). The [max 32-bit int is 2,147,483,647](https://en.wikipedia.org/wiki/2,147,483,647), and `100012345678` is significantly bigger than `2147483647`. If you really have numbers larger than 32-bit (rather, if you need that many significant digits), this isn't the droid you're looking for. This is a quick and dirty (and fast) answer for, say, 4-5 sig digits. For potentially overkill-ish perfection, [try the accepted answer](https://stackoverflow.com/a/4912870/1028230). ;^D – ruffin Dec 15 '20 at 21:47
11

I thought I'd throw in an answer using | since it is simple and works well.

truncate = function(number, places) {
  var shift = Math.pow(10, places);

  return ((number * shift) | 0) / shift;
};
Daniel X Moore
  • 14,637
  • 17
  • 80
  • 92
  • 1
    Good call. Using a bitwise operator coerces the value into an int, and `or`ing with 0 means "just keep what I've already got". Does what my `~~` answer does, but with a single bitwise operation. Though it has the same limitation as written too: [We can't go over 2^31](http://stackoverflow.com/questions/7487977). – ruffin Jun 12 '15 at 19:37
  • 1
    not correct when `truncate((10 * 2.9) / 100);` this code return 0.28 instead of 0.29 https://jsfiddle.net/9pf0732d/ – Alex Jun 29 '19 at 18:06
  • @Alex As I'm guessing you realize... [welcome to JavaScript!](https://stackoverflow.com/q/588004/1028230). There are fixes. Perhaps you'd like to share one? :D – ruffin Jun 30 '19 at 17:34
  • @ruffin I know about this issue =) I thought this answer was the solution to this problem. Unfortunately, I haven’t found an exact solution yet, everywhere there is such a problem. – Alex Jun 30 '19 at 21:17
9

Truncate using bitwise operators:

~~0.5 === 0
~~(-0.5) === 0
~~14.32794823 === 14
~~(-439.93) === -439
John Strickler
  • 25,151
  • 4
  • 52
  • 68
9

@Dogbert's answer can be improved with Math.trunc, which truncates instead of rounding.

There is a difference between rounding and truncating. Truncating is clearly the behaviour this question is seeking. If I call truncate(-3.14) and receive -4 back, I would definitely call that undesirable. – @NickKnowlson

var a = 5.467;
var truncated = Math.trunc(a * 100) / 100; // = 5.46
var a = -5.467;
var truncated = Math.trunc(a * 100) / 100; // = -5.46
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • 1
    That doesn't work in all cases i.e. console.log(Math.trunc(9.28 * 100) / 100); // 9.27 – Mike Makuch Apr 02 '18 at 22:47
  • 1
    @MikeMakuch that's not a problem with `Math.trunc`, but rather than `9.28 * 100` is `927.9999` rather than `928`. You might want to read over [The Perils of Floating Point](http://www.lahey.com/float.htm) – zurfyx Apr 03 '18 at 06:56
6

I think this function could be a simple solution:

function trunc(decimal,n=2){
  let x = decimal + ''; // string 
  return x.lastIndexOf('.')>=0?parseFloat(x.substr(0,x.lastIndexOf('.')+(n+1))):decimal; // You can use indexOf() instead of lastIndexOf()
}

console.log(trunc(-241.31234,2));
console.log(trunc(241.312,5));
console.log(trunc(-241.233));
console.log(trunc(241.2,0));  
console.log(trunc(241));
  • Two years after this was posted but stumbled across this when I was trying to work out the best way using Math.trunc, regex, etc. I really like this solution. Dead simple but works perfectly (for my use case anyway). – giles123 Jul 19 '18 at 08:43
  • Don't forget to account for n=0 though. – giles123 Jul 19 '18 at 09:31
6

I wrote an answer using a shorter method. Here is what I came up with

function truncate(value, precision) {
    var step = Math.pow(10, precision || 0);
    var temp = Math.trunc(step * value);

    return temp / step;
}

The method can be used like so

truncate(132456.25456789, 5)); // Output: 132456.25456
truncate(132456.25456789, 3)); // Output: 132456.254
truncate(132456.25456789, 1)); // Output: 132456.2   
truncate(132456.25456789));    // Output: 132456

Or, if you want a shorter syntax, here you go

function truncate(v, p) {
    var s = Math.pow(10, p || 0);
    return Math.trunc(s * v) / s;
}
4
Number.prototype.trim = function(decimals) {
    var s = this.toString();
    var d = s.split(".");
    d[1] = d[1].substring(0, decimals);
    return parseFloat(d.join("."));
}

console.log((5.676).trim(2)); //logs 5.67
Max Zlotskiy
  • 114
  • 5
4

I'm a bit confused as to why there are so many different answers to such a fundamentally simple question; there are only two approaches which I saw which seemed to be worth looking at. I did a quick benchmark to see the speed difference using https://jsbench.me/.

This is the solution which is currently (9/26/2020) flagged as the answer:

function truncate(n, digits) {
    var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
        m = n.toString().match(re);
    return m ? parseFloat(m[1]) : n.valueOf();
};

[   truncate(5.467,2),
    truncate(985.943,2),
    truncate(17.56,2),
    truncate(0, 1),
    truncate(1.11, 1) + 22];

However, this is doing string and regex stuff, which is usually not very efficient, and there is a Math.trunc function which does exactly what the OP wants just with no decimals. Therefore, you can easily use that plus a little extra arithmetic to get the same thing.

Here is another solution I found on this thread, which is the one I would use:

function truncate(n, digits) {
    var step = Math.pow(10, digits || 0);
    var temp = Math.trunc(step * n);

    return temp / step;
}

[   truncate(5.467,2),
    truncate(985.943,2),
    truncate(17.56,2),
    truncate(0, 1),
    truncate(1.11, 1) + 22];
    

The first method is "99.92% slower" than the second, so the second is definitely the one I would recommend using.

Okay, back to finding other ways to avoid work...

screenshot of the benchmark

taxilian
  • 14,229
  • 4
  • 34
  • 73
3

I found a problem: considering the next situation: 2.1 or 1.2 or -6.4

What if you want always 3 decimals or two or wharever, so, you have to complete the leading zeros to the right

// 3 decimals numbers
0.5 => 0.500

// 6 decimals
0.1 => 0.10000

// 4 decimales
-2.1 => -2.1000

// truncate to 3 decimals
3.11568 => 3.115

This is the fixed function of Nick Knowlson

function truncateDecimals (num, digits) 
{
    var numS = num.toString();
    var decPos = numS.indexOf('.');
    var substrLength = decPos == -1 ? numS.length : 1 + decPos + digits;
    var trimmedResult = numS.substr(0, substrLength);
    var finalResult = isNaN(trimmedResult) ? 0 : trimmedResult;

    // adds leading zeros to the right
    if (decPos != -1){
        var s = trimmedResult+"";
        decPos = s.indexOf('.');
        var decLength = s.length - decPos;

            while (decLength <= digits){
                s = s + "0";
                decPos = s.indexOf('.');
                decLength = s.length - decPos;
                substrLength = decPos == -1 ? s.length : 1 + decPos + digits;
            };
        finalResult = s;
    }
    return finalResult;
};

https://jsfiddle.net/huttn155/7/

juanpscotto
  • 990
  • 1
  • 13
  • 32
3

The answer by @kirilloid seems to be the correct answer, however, the main code needs to be updated. His solution doesn't take care of negative numbers (which someone did mention in the comment section but has not been updated in the main code).

Updating that to a complete final tested solution:

Number.prototype.toFixedDown = function(digits) {
    var re = new RegExp("([-]*\\d+\\.\\d{" + digits + "})(\\d)"),
    m = this.toString().match(re);
    return m ? parseFloat(m[1]) : this.valueOf();
};

Sample Usage:

var x = 3.1415629;
Logger.log(x.toFixedDown(2)); //or use whatever you use to log

Fiddle: JS Number Round down

PS: Not enough repo to comment on that solution.

ProgWiz
  • 31
  • 1
  • 6
3
function toFixed(number, digits) {
    var reg_ex = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)")
    var array = number.toString().match(reg_ex);
    return array ? parseFloat(array[1]) : number.valueOf()
}

var test = 10.123456789
var __fixed = toFixed(test, 6)
console.log(__fixed)
// => 10.123456
Flavio
  • 506
  • 4
  • 9
2

Here my take on the subject:

convert.truncate = function(value, decimals) {
  decimals = (decimals === undefined ? 0 : decimals);
  return parseFloat((value-(0.5/Math.pow(10, decimals))).toFixed(decimals),10);
};

It's just a slightly more elaborate version of

(f - 0.005).toFixed(2)
opensas
  • 60,462
  • 79
  • 252
  • 386
2

Here is simple but working function to truncate number upto 2 decimal places.

           function truncateNumber(num) {
                var num1 = "";
                var num2 = "";
                var num1 = num.split('.')[0];
                num2 = num.split('.')[1];
                var decimalNum = num2.substring(0, 2);
                var strNum = num1 +"."+ decimalNum;
                var finalNum = parseFloat(strNum);
                return finalNum;
            }
RohannG
  • 669
  • 7
  • 12
2

The resulting type remains a number...

/* Return the truncation of n wrt base */
var trunc = function(n, base) {
    n = (n / base) | 0;
    return base * n;
};
var t = trunc(5.467, 0.01);
Bob Lyon
  • 44
  • 3
2

Lodash has a few Math utility methods that can round, floor, and ceil a number to a given decimal precision. This leaves off trailing zeroes.

They take an interesting approach, using the exponent of a number. Apparently this avoids rounding issues.

(Note: func is Math.round or ceil or floor in the code below)

// Shift with exponential notation to avoid floating-point issues.
var pair = (toString(number) + 'e').split('e'),
    value = func(pair[0] + 'e' + (+pair[1] + precision));

pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));

Link to the source code

Matthias
  • 13,607
  • 9
  • 44
  • 60
2
const TO_FIXED_MAX = 100;

function truncate(number, decimalsPrecison) {
  // make it a string with precision 1e-100
  number = number.toFixed(TO_FIXED_MAX);

  // chop off uneccessary digits
  const dotIndex = number.indexOf('.');
  number = number.substring(0, dotIndex + decimalsPrecison + 1);

  // back to a number data type (app specific)
  return Number.parseFloat(number);
}

// example
truncate(0.00000001999, 8);
0.00000001

works with:

  • negative numbers
  • very small numbers (Number.EPSILON precision)
givanse
  • 14,503
  • 8
  • 51
  • 75
2

You can use toFixed(2) to convert your float to a string with 2 decimal points. Then you can wrap that in floatParse() to convert that string back to a float to make it usable for calculations or db storage.

const truncatedNumber = floatParse(num.toFixed(2))

I am not sure of the potential drawbacks of this answer like increased processing time but I tested edge cases from other comments like .29 which returns .29 (not .28 like other solutions). It also handles negative numbers.

meisenman
  • 1,818
  • 1
  • 15
  • 25
1

The one that is mark as the solution is the better solution I been found until today, but has a serious problem with 0 (for example, 0.toFixedDown(2) gives -0.01). So I suggest to use this:

Number.prototype.toFixedDown = function(digits) {
  if(this == 0) {
    return 0;
  }
  var n = this - Math.pow(10, -digits)/2;
  n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
  return n.toFixed(digits);
}
Sebastián Rojas
  • 2,776
  • 1
  • 25
  • 34
1

Here is what I use:

var t = 1;
for (var i = 0; i < decimalPrecision; i++)
    t = t * 10;

var f = parseFloat(value);
return (Math.floor(f * t)) / t;
Steve
  • 11
  • 1
1

You can work with strings. It Checks if '.' exists, and then removes part of string.

truncate (7.88, 1) --> 7.8

truncate (7.889, 2) --> 7.89

truncate (-7.88, 1 ) --> -7.88

function  truncate(number, decimals) {
    const tmp = number + '';
    if (tmp.indexOf('.') > -1) {
        return +tmp.substr(0 , tmp.indexOf('.') + decimals+1 );
    } else {
        return +number
    }
 }
1
function trunc(num, dec) {
  const pow = 10 ** dec
  return Math.trunc(num * pow) / pow
}

// ex.
trunc(4.9634, 1) // 4.9
trunc(4.9634, 2) // 4.96
trunc(-4.9634, 1) // -4.9
webm94
  • 11
  • 1
0

just to point out a simple solution that worked for me

convert it to string and then regex it...

var number = 123.45678;
var number_s = '' + number;
var number_truncated_s = number_s.match(/\d*\.\d{4}/)[0]
var number_truncated = parseFloat(number_truncated_s)

It can be abbreviated to

var number_truncated = parseFloat(('' + 123.4568908).match(/\d*\.\d{4}/)[0])
Sergio Campamá
  • 746
  • 1
  • 7
  • 14
0

Here is an ES6 code which does what you want

const truncateTo = (unRouned, nrOfDecimals = 2) => {
      const parts = String(unRouned).split(".");

      if (parts.length !== 2) {
          // without any decimal part
        return unRouned;
      }

      const newDecimals = parts[1].slice(0, nrOfDecimals),
        newString = `${parts[0]}.${newDecimals}`;

      return Number(newString);
    };

// your examples 

 console.log(truncateTo(5.467)); // ---> 5.46

 console.log(truncateTo(985.943)); // ---> 985.94

// other examples 

 console.log(truncateTo(5)); // ---> 5

 console.log(truncateTo(-5)); // ---> -5

 console.log(truncateTo(-985.943)); // ---> -985.94
Cristian Sima
  • 11
  • 1
  • 2
0

Suppose you want to truncate number x till n digits.

Math.trunc(x * pow(10,n))/pow(10,n);
bfontaine
  • 18,169
  • 13
  • 73
  • 107
Mohit Vachhani
  • 108
  • 1
  • 2
  • 5
-1
Number.prototype.truncate = function(places) {
  var shift = Math.pow(10, places);

  return Math.trunc(this * shift) / shift;
};
Dercni
  • 1,216
  • 3
  • 18
  • 38
-2
  function toFix(num,n)
    {
    beforeDecimal=num.toString().split(".",[2])[0];
    afterDecimal=num.toString().split(".",[2])[1];
    updateAfterDecimal="";
    if(afterDecimal != undefined && afterDecimal.length >= n )
        updateAfterDecimal =afterDecimal.slice(0,n);
    if(afterDecimal != undefined && afterDecimal.length < n )
        updateAfterDecimal= afterDecimal.padEnd(n,"0");
    if(afterDecimal== undefined)
        updateAfterDecimal=updateAfterDecimal.padEnd(n,"0");
    console.log(`${beforeDecimal}.${updateAfterDecimal}`);
    }
    toFix(5.12365889,5); 
Wajid
  • 593
  • 3
  • 11
  • This code will add padding "0" is places after decimal is than what is required. – Ankur144 Jun 22 '21 at 03:59
  • eg- for 3 decimal places (with padding"0") 5.3 --->5.300 0.01 ---->0.010 0.00001 --->0.000 5.32195--->5.321 -3.66696---> -3.666 – Ankur144 Jun 22 '21 at 04:07
-3

let number=5.467; // we want to truncate into 5.46
let result=+number.toString().split("").splice(0,4).join('');
console.log(result);
bfontaine
  • 18,169
  • 13
  • 73
  • 107