I am trying to round large digits. For instance, if I have this number:
12,645,982
I want to round this number and display it as:
13 mil
Or, if I have this number:
1,345
I want to round it and display it as:
1 thousand
How do I do this in JavaScript or jQuery?
How do you round to the nearest thousandth in Javascript? round(1000*X)/1000; // round X to thousandths To convert a number to a string that represents your number with exactly n decimal places, use the toFixed method.
The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).
The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in the above syntax using the '. ' operator.
Here is a utility function to format thousands, millions, and billions:
function MoneyFormat(labelValue)
{
// Nine Zeroes for Billions
return Math.abs(Number(labelValue)) >= 1.0e+9
? Math.abs(Number(labelValue)) / 1.0e+9 + "B"
// Six Zeroes for Millions
: Math.abs(Number(labelValue)) >= 1.0e+6
? Math.abs(Number(labelValue)) / 1.0e+6 + "M"
// Three Zeroes for Thousands
: Math.abs(Number(labelValue)) >= 1.0e+3
? Math.abs(Number(labelValue)) / 1.0e+3 + "K"
: Math.abs(Number(labelValue));
}
Usage:
var foo = MoneyFormat(1355);
//Reformat result to one decimal place
console.log(parseFloat(foo).toPrecision(2) + foo.replace(/[^B|M|K]/g,""))
References
ECMAScript-5: Annex A
Displaying numbers in JavaScript
Numeral JS .. If someone checks this out please check numeral Js. you just have to include the script and then its just one lineof code
numeral(yourNumber).format('0.0a')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With