Truncate (Not Round Off) Decimal Numbers in JavaScript

Truncate number to two decimal places without rounding

Convert the number into a string, match the number up to the second decimal place:

function calc(theform) {    var num = theform.original.value, rounded = theform.rounded    var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]    rounded.value = with2Decimals}
<form onsubmit="return calc(this)">Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" /><br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly></form>

Truncate (not round off) decimal numbers in javascript

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

Truncate float (not rounded) to 2 decimal places

This can be done by dropping the extra digits you don't want by using multiplication and division. For example, if you want 0.994 to be 0.99, you can multiply by 100 (to cover 2 decimal places), then truncate the number, and then divide it back by 100 to it to the original decimal place.

example:

  0.994 * 100 = 99.4
99.4 truncated = 99.0
99.0 / 100 = 0.99

So here is a function that will do that:

const truncateByDecimalPlace = (value, numDecimalPlaces) =>
Math.trunc(value * Math.pow(10, numDecimalPlaces)) / Math.pow(10, numDecimalPlaces)

console.log(truncateByDecimalPlace(0.996, 2)) // 0.99

Obtain two decimal places in JavaScript without rounding to the next bigger number

You could use Math.floor and some additional arithmetics:

Math.floor(15.7784514000 * 100) / 100

Or convert the number into a string, match the number up to the second decimal place and turn it back into a number:

Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/))

Then you can still call toFixed to get a string with a fixed number of decimal places.

var num1 = Math.floor(15.7784514000 * 100) / 100;console.log(num1);
var num2 = Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/));console.log(num2)console.log(num2.toFixed(2))

toFixed method without rounding to five digit

You can use an apropriate factor and floor it and return the result of the division.

Basically this solution moves the point to the left with a factor of 10^d and gets an integer of that and divided the value with the former factor to get the right digits.

function getFlooredFixed(v, d) {    return (Math.floor(v * Math.pow(10, d)) / Math.pow(10, d)).toFixed(d);}
var x = 2.305185185185195;
document.write(getFlooredFixed(x, 5));

javascript - how to prevent toFixed from rounding off decimal numbers

Round the number (down) to the nearest cent first:

val = Math.floor(100 * val) / 100;

EDIT It's been pointed out that this fails for e.g. 1.13. I should have known better myself!

This fails because the internal floating point representation of 1.13 is very slightly less than 1.13 - multiplying that by 100 doesn't produce 113 but 112.99999999999998578915 and then rounding that down takes it to 1.12

Having re-read the question, it seems that you're really only trying to perform input validation (see below), in which case you should use normal form validation techniques and you shouldn't use .toFixed() at all. That function is for presenting numbers, not calculating with them.

$('#txtAmount').on('keypress', function (e) {
var k = String.fromCharCode(e.charCode);
var v = this.value;
var dp = v.indexOf('.');

// reject illegal chars
if ((k < '0' || k > '9') && k !== '.') return false;

// reject any input that takes the length
// two or more beyond the decimal point
if (dp >= 0 && v.length > dp + 2) {
return false;
}

// don't accept >1 decimal point, or as first char
if (k === '.' && (dp >= 0 || v.length === 0)) {
return false;
}
});

Truncate Decimal number not Round Off

double d = 2.22977777;
d = ( (double) ( (int) (d * 1000.0) ) ) / 1000.0 ;

Of course, this won't work if you're trying to truncate rounding error, but it should work fine with the values you give in your examples. See the first two answers to this question for details on why it won't work sometimes.

How to truncate (not round) a particular number after decimal point using javascript

Well try this.
See if it works for you

var x = -81.82637799999999;
x = x.toString(); // convert to string
alert(x.length);
x = x.substring(0, x.length - 1); // cut out last character
alert(x.length);
x = parseFloat(x); // convert it back to float

https://jsfiddle.net/9sngtp3n/1/

How to truncate decimals in JavaScript without Math library?

Make it simple

const trunc = (n, decimalPlaces) => {
const decimals = decimalPlaces ? decimalPlaces : 2;
const asString = n.toString();
const pos = asString.indexOf('.') != -1 ? asString.indexOf('.') + decimals + 1 : asString.length;
return parseFloat(n.toString().substring(0, pos));
};

console.log(trunc(3.14159265359));
console.log(trunc(11.1111111));
console.log(trunc(3));
console.log(trunc(11));
console.log(trunc(3.1));
console.log(trunc(11.1));
console.log(trunc(3.14));
console.log(trunc(11.11));
console.log(trunc(3.141));
console.log(trunc(11.111));


Related Topics



Leave a reply



Submit