-3

Currently using below code for conversion of number to currency. The only issue is if I have 1000 it is giving 1000 instead I need 1k.

Current implementation 1000 - 1000

Need 1000 - 1k

Tried in lot many ways to get it done but unable to resolve.

var number = 12345678910;

var digits = 2;
var suffix = ["", "K.", "M.", "B."];

var nbDigits = parseInt(Math.log(number)/Math.LN10);
var power = nbDigits - nbDigits%3;

var tmp = number/ Math.pow(10, power);
var suffixIndex = Math.min(3, power/3);

var result = "$" + tmp.toFixed(digits) + " " + suffix[suffixIndex];

I got this solution from this link

Kartheek Sarabu
  • 3,886
  • 8
  • 33
  • 66
  • Read this : https://stackoverflow.com/questions/2685911/is-there-a-way-to-round-numbers-into-a-reader-friendly-format-e-g-1-1k https://stackoverflow.com/questions/9345136/1000000-to-1m-and-1000-to-1k-and-so-on-in-js – Sachith Wickramaarachchi Feb 21 '19 at 11:04
  • Possible duplicate of [Is there a way to round numbers into a reader friendly format? (e.g. $1.1k)](https://stackoverflow.com/questions/2685911/is-there-a-way-to-round-numbers-into-a-reader-friendly-format-e-g-1-1k) – Sachith Wickramaarachchi Feb 21 '19 at 11:05

1 Answers1

1

Just simplify calculation of number of digits:

// From:
var nbDigits = parseInt(Math.log(number)/Math.LN10);

// To:
var nbDigits1 = Math.log10(number);

That'll give you the number of digits, without rounding errors. It does return $1.00 K. for 1000.

Hope this helps!

Adi B
  • 1,189
  • 13
  • 32
  • why not take [`Math.log10`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10) directly? – Nina Scholz Feb 21 '19 at 15:31