JavaScript provides part of the number format method, but not perfect, you can look at the use of the number object, which provides some formatted output of numbers, several functions are as follows:
Toexponential ([fractiondigits]): Returns the number in scientific notation format, where the fractiondigits value is retained after the decimal point.
ToFixed ([fractiondigits]): Returns a number to the specified number of decimal places, where the fractiondigits value is retained after the decimal point.
Toprecision ([precision]): Returns a number to the specified precision (this precision does not refer to a few after the decimal point), where precision is the specified precision value.
If you don't use the above function, I'll simply give you an example:
The code is as follows |
Copy Code |
var num=56.45678; var rs1=num.toexponential (2);//rs1 value is 5.65e+1 var rs2=num.tofixed (2);//rs value is 56.45 var rs3=num.toprecision (2);//rs value is 56 |
JavaScript formats two-bit decimal code.
The code is as follows |
Copy Code |
function Formatfloat (SRC, POS) { Return Math.Round (Src*math.pow, POS))/math.pow (POS); } Alert (Formatfloat ("11111.2222", 2)); Example |
/**
* Data Format
*
* @param number
* @param n retains several decimal places (n > 0)
*/
function Numformat (number, n) {
var number = Math.Round (number * MATH.POW (n))/Math.pow (n);
Number = Number.tostring ();
The code is as follows |
Copy Code |
if (Number.indexof ('. ') = = 1) { Return number + '. ' + Math.pow (n). toString (). substr (1); }else{ Return number + MATH.POW (n-(Number.length-1-Number.indexof ('. '))). ToString (). substr (1); } } |
Example 2
The code is as follows |
Copy Code |
function Number_format (s) { if (/[^0-9\.\-]/.test (s)) return invalid Value "; s=s.replace (/^ (\d*) $/, "$"); s= (s+). Replace (/(\d*\.\d\d) \d*/, "$"); s=s.replace (".", ","); var re=/(\d) (\d{3},)/; while (Re.test (s)) S=s.replace (Re, "$1,$2"); S=s.replace (/, (\d\d) $/, ". $"); return S.replace (/^\./, "0.") } alert (Number_format (' -123456.789 ')); |