A solution for multiplying floating point Numbers in Javascript

  • 2020-03-30 03:08:15
  • OfStack

Multiplying floating point Numbers in Javascript is an interesting thing.

There are many ways to multiply floating point Numbers, and here is a solution that I think is good:

function FxF(f1, f2) {
    f1 += '';
    f2 += '';
    var f1Len = f1.split('.')[1].length,
        f2Len = f2.split('.')[1].length;
    if (f1Len) {
        f1 = f1.replace('.', '');
    if (f2Len) {
        f2 = f2.replace('.', '');
    return f1 * f2 / Math.pow(10, f1Len + f2Len);

The basic idea

The basic idea is to turn all floating point Numbers into integers and then divide by the equivalent of 10 to the NTH power. N is (the sum of the following lengths of two floating point Numbers).

Related articles: