JS 保留2位小数点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hlx20080808/article/details/87932112

 

源代码:

//保留2位小数点
function moneyFormat(val) {  
//	如果是空的,则返回0.00          
	if(val == "" || val == null) {               
		return "0.00";            
	}   
	//获得小数值         
	var value = Math.round(parseFloat(val) * 100) / 100; 
	   
	//截取小数点后面的值        
	var xsd = value.toString().split(".");    
	
	//如果为1,则加0.00        
	if(xsd.length == 1) {               
		value = value.toString() + ".00";               
		return value;            
	}          
	  
	if(xsd.length > 1) {   
		//如果小数点小于2位,就加0            
		if(xsd[1].length < 2) {                  
			value = value.toString() + "0";               
		}               
		return value;            
	}         
}

猜你喜欢

转载自blog.csdn.net/hlx20080808/article/details/87932112