Html & Script

자바스크립트 javascript number_format

컨텐츠 정보

  • 10,969 조회
  • 1 댓글
  • 0 추천
  • 목록

본문

Formatting numbers in JavaScript


Overview of formatting numbers in JavaScript

JavaScript doesn't have many built-in methods to format numbers. Most of the time customized code needs to be used. Refer below for a couple rounding methods that JavaScript offers, then next up is some custom code I wrote to do more advanced formatting.

Round to a certain number of places

For rounding decimals you can use the built-in JavaScript methods toFixed or toPrecision.

var num = 10;
var result = num.toFixed(2); // result will equal 10.00

num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2

num = 5000.2349;
result = num.toPrecision(4); // result will equal 5000

num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2

Learn more

Add commas

This functionality is not built into JavaScript, so custom code needs to be used. The following is one way of adding commas to a number, and returning a string.

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

Learn more

Multi-functional number format script

  • commas (configurable digit grouping separators and decimal symbols)
  • certain decimal precision that leave trailing zeros
  • various formats for currency and negative values
  • input can be a string that's already formatted

Learn more

Interactive example

Syntax information

관련자료

댓글 1

nuno님의 댓글

function number_format(v){
 v = v+"";
 var arr = v.split(".");
 if(arr.length > 1)
 {
 var str = arr[0];
 }else{
 var str =v;
 }
        str = ""+str+"";
        var retValue = "";
        for(i=0; i<str.length; i++){
 if(i > 0 && (i%3)==0) {
 retValue = str.charAt(str.length - i -1) + "," + retValue;
 } else {
 retValue = str.charAt(str.length - i -1) + retValue;
 }
 }

 if(arr.length > 1)
 {
  return retValue +"." +arr[1];
 }else{
  return retValue;
 }
 
}
Today's proverb
착하게 산다는 것이 어수룩한 삶은 아닌지, 지혜롭게 산다는 것이 이기적인 삶의 태도가 아닌지 항상 생각해 봐야 한다.