简体   繁体   中英

Need to convert number to currency

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM