Truncate (not round off) decimal numbers in javascript
Asked Answered
F

32

132

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.

Fetching answered 6/2, 2011 at 10:42 Comment(2)
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.Encore
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.Tejeda
V
62

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);
}
Vernettaverneuil answered 6/2, 2011 at 11:1 Comment(11)
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.Retch
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.Mcandrew
Thanks for report, this is an important notice. Unfortunately 17.56 != 17.55 - 0.01. I updated the code.Vernettaverneuil
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.Desta
Note that this function removes the negative sign. Ex: (-10.2131).toFixedDown(2) // ==> 10.21.Evacuation
Also, (1e-7).toFixedDown(0) // ==> 1e-7. Does that for 1e-(>=7) (ex: 1e-8, 1e-9, ...).Evacuation
This is solution is good enough in my case, I only changed the regExp a little: "(-*\\d+\\.\\d{" + digits + "})(\\d)"Levator
I'd write "([-+]?\\d+\\.\\d{" + digits + "})(\\d)" then.Vernettaverneuil
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.Tutt
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.Jacobo
I'd write "([-+]?\\d*\\.\\d{" + digits + "})(\\d)" => Ex: .00 , .00009, .999999Manoff
D
80

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

Desta answered 10/2, 2012 at 17:29 Comment(9)
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.Retch
It's good for exactly what it says - when you want to truncate decimals rather than rounding.Desta
Not going to work with 17.56 because browser gives 17.56 * 100 = 1755.9999999999998 not 1756Mcandrew
Good point shendz. I've updated my answer with a solution that eliminates all floating-point error for those who need that.Desta
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.Homager
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.Desta
if(isNan( is missing a closing bracketLionhearted
+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);Mllly
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!Desta
V
62

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);
}
Vernettaverneuil answered 6/2, 2011 at 11:1 Comment(11)
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.Retch
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.Mcandrew
Thanks for report, this is an important notice. Unfortunately 17.56 != 17.55 - 0.01. I updated the code.Vernettaverneuil
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.Desta
Note that this function removes the negative sign. Ex: (-10.2131).toFixedDown(2) // ==> 10.21.Evacuation
Also, (1e-7).toFixedDown(0) // ==> 1e-7. Does that for 1e-(>=7) (ex: 1e-8, 1e-9, ...).Evacuation
This is solution is good enough in my case, I only changed the regExp a little: "(-*\\d+\\.\\d{" + digits + "})(\\d)"Levator
I'd write "([-+]?\\d+\\.\\d{" + digits + "})(\\d)" then.Vernettaverneuil
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.Tutt
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.Jacobo
I'd write "([-+]?\\d*\\.\\d{" + digits + "})(\\d)" => Ex: .00 , .00009, .999999Manoff
W
41
var a = 5.467;
var truncated = Math.floor(a * 100) / 100; // = 5.46
Walker answered 6/2, 2011 at 10:44 Comment(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 https://mcmap.net/q/47356/-truncate-not-round-off-decimal-numbers-in-javascriptDesta
Why undesirable? Changing the direction of rounding when you go below 0, causes all sorts of arithmetical artefacts.Retch
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.Desta
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"Sclera
var a = 65.1 var truncated = Math.floor(a * 100) / 100; // = 65.09 Hence this is not a correct solutionShakira
H
21

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

(f - 0.005).toFixed(2)
Hellish answered 6/2, 2011 at 10:47 Comment(2)
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.467Desta
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.Scylla
C
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
Courtier answered 13/3, 2016 at 1:34 Comment(3)
I like this solution, but just keep in mind that it's not fully supported by all browsers. (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)Jdavie
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.Crossman
@Crossman pff yeah, wtf :| I'm currently having hard times solving this issue, so I think I'll fallback as you proposed to strings :)Sooty
D
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.

Develop answered 22/5, 2013 at 16:20 Comment(5)
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.Kiel
truncator((10 * 2.9) / 100, 2) return 0.28 instead of 0.29 ... jsfiddle.net/25tgrzq1Inexpensive
Not working for me, truncator(1000.12345678, 7) returns 141.1299975Crossman
@Inexpensive If you want to avoid floating point errors, use a decimal type. Or I guess we could rewrite to use string manipulation, but that seems insane. You'll notice similar answers have the same issue.Develop
@Crossman That's because JavaScript uses 32-bit ints for bitwise operators. The max 32-bit int is 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. ;^DDevelop
P
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;
};
Promiscuity answered 18/3, 2014 at 0:15 Comment(4)
Good call. Using a bitwise operator coerces the value into an int, and oring 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.Develop
not correct when truncate((10 * 2.9) / 100); this code return 0.28 instead of 0.29 jsfiddle.net/9pf0732dInexpensive
@Inexpensive As I'm guessing you realize... welcome to JavaScript!. There are fixes. Perhaps you'd like to share one? :DDevelop
@Develop 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.Inexpensive
S
10

Truncate using bitwise operators:

~~0.5 === 0
~~(-0.5) === 0
~~14.32794823 === 14
~~(-439.93) === -439
Siliqua answered 28/11, 2016 at 14:31 Comment(2)
How does this work reference: #7488477Muttonchops
How does it truncate something to, say, 2 decimal places?Messidor
I
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
Inextensible answered 14/1, 2017 at 17:33 Comment(2)
That doesn't work in all cases i.e. console.log(Math.trunc(9.28 * 100) / 100); // 9.27Turbinal
@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 PointInextensible
F
7

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;
}
Ferino answered 19/7, 2019 at 16:9 Comment(2)
this is the method that I would have expected to useTeplitz
Same issue as others pointed out, truncate(0.29, 2) gives you 0.28.Crossman
S
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));
Summerville answered 16/4, 2018 at 16:58 Comment(2)
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).Gobbledygook
Don't forget to account for n=0 though.Gobbledygook
P
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
Polyglot answered 23/11, 2014 at 19:23 Comment(2)
I like that this works with strings, thus eliminating the nuances of floating point numbers. Thanks!Regenaregency
console.log((-5).trim(2)); throws Uncaught TypeError: d[1] is undefinedCrossman
T
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

Teplitz answered 26/9, 2020 at 20:17 Comment(0)
N
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/

Novelia answered 26/3, 2015 at 21:21 Comment(1)
x = 0.0000 test truncateDecimals (x, 2) fails. returns 0. not as expected 0.00Gaikwar
B
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.

Bulley answered 3/10, 2017 at 12:29 Comment(0)
E
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
Ewer answered 14/3, 2018 at 0:9 Comment(0)
T
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)
Torietorii answered 15/5, 2013 at 6:4 Comment(0)
C
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;
            }
Charlyncharm answered 22/7, 2014 at 9:52 Comment(0)
D
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);
Dunbarton answered 25/4, 2015 at 22:13 Comment(0)
D
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

Dish answered 26/7, 2018 at 4:47 Comment(0)
H
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)
Haply answered 26/12, 2019 at 22:52 Comment(0)
B
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.

Breakable answered 24/9, 2022 at 19:37 Comment(0)
P
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);
}
Pentatomic answered 23/4, 2014 at 21:28 Comment(0)
O
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;
Olathe answered 17/7, 2014 at 11:47 Comment(0)
H
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
    }
 }
Heptachord answered 10/1, 2020 at 19:27 Comment(0)
V
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
Vulvitis answered 31/1, 2022 at 2:46 Comment(2)
Easy to read and elegant - kudos!Lectra
Doesn't work - trunc(1304.35,2) // 1304.34. Which is because num * pow -> 1304.35 * 100 // 130434.99999999999.Thingumabob
D
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])
Dissection answered 7/6, 2013 at 23:11 Comment(0)
D
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
Disentwine answered 30/8, 2016 at 17:19 Comment(0)
P
0

Suppose you want to truncate number x till n digits.

Math.trunc(x * pow(10,n))/pow(10,n);
Pandemonium answered 25/3, 2021 at 11:2 Comment(0)
E
-1
Number.prototype.truncate = function(places) {
  var shift = Math.pow(10, places);

  return Math.trunc(this * shift) / shift;
};
Explanatory answered 3/1, 2017 at 5:55 Comment(0)
D
-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); 
Divan answered 22/6, 2021 at 3:58 Comment(2)
This code will add padding "0" is places after decimal is than what is required.Divan
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.666Divan
K
-3

let number=5.467; // we want to truncate into 5.46
let result=+number.toString().split("").splice(0,4).join('');
console.log(result);
Korney answered 17/6, 2021 at 23:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.