icy
icy

Reputation: 1446

javascript toFixed()

In many case toFixed() fail cause of floating point in javascript math.

I found this solution:

function toFixed(decimalPlaces) {
var factor = Math.pow(10, decimalPlaces || 0);
var v = (Math.round(Math.round(this * factor * 100) / 100) / factor).toString();
if (v.indexOf('.') >= 0) {
    return v + factor.toString().substr(v.length - v.indexOf('.'));
}
return v + '.' + factor.toString().substr(1);
}

and this:

function toFixed(num, fixed) {
var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
return num.toString().match(re)[0];
}

There are other approaches? I have to be certain that performs well in any case. Also in borderline-cases.

EDIT: https://github.com/MikeMcl/decimal.js @Tschallacka

Number.prototype.toFixed = function(fixed) {
x = new Decimal(Number(this));
return x.toFixed(fixed);
};

Upvotes: 0

Views: 744

Answers (1)

Tschallacka
Tschallacka

Reputation: 28722

I suggest you use a library:

https://github.com/MikeMcl/decimal.js

I found it very dependable when working with finanical data.

Working with floating point numbers is always difficult, but there are several solutions out there. I suggest you use an existin library that is well maintained, which already has had it's baby teeth knocked out.

Assuming you added decimal.js you can do this for financial values.

/**
 * @var input float
 */
function toFixed(input) {
  var dec = new Decimal(input);
  return dec.toFixed(2);
}
console.log("float to fixed 2 decimal places: ",toFixed(200.23546546546));



function toFixed2(decimalPlaces) {
  var dec = new Decimal(1);
  return dec.toFixed(decimalPlaces);
}
console.log("get a fixed num: ",toFixed2(10));

Number.prototype.toFixed = function(fixed) {
x = new Decimal(Number(this));
return x.toFixed(fixed);
};

var num = new Number(10.4458);
console.log("Number to fixed via prototyped method: ",num.toFixed(2));

var x = 44.456
console.log('Number to fixed via inderect number casting:' ,x.toFixed(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/7.1.1/decimal.min.js"></script>

Upvotes: 1

Related Questions