[thelist] Just a quick WTF: How to cut off a number after a certain amount of decimals

Christian Heilmann codepo8 at gmail.com
Tue Mar 28 08:51:07 CST 2006


I just had a good giggle doing a code review of an older JavaScript.
The task was to cut off a number after a certain amount of decimals,
not round it up or down.

So, 3.1415927 in the case of two decimals should become 3.14 and so
should 3.149.

The first iteration had this function to do that:
	function getDecimalCut(val,d){
		var x;
		switch(d){
			case 1:
				x=10;
			break;		
			case 2:
				x=100;
			break;		
			case 3:
				x=1000;
			break;		
			case 4:
				x=10000;
			break;		
			case 5:
				x=100000;
			break;
			case 6:
				x=1000000;
			break;
			case 7:
				x=10000000;
			break;
			case 8:
				x=100000000;
			break;
			case 9:
				x=1000000000;
			break;
			case 10:
				x=10000000000;
			break;
			default:
				x=100;
			break;		
		}
		return parseInt(val*x)/x;
	}

Which shows a dedication to our coding practices in terms of
indentation at least, albeit not being very dynamic.

The second round developer heard about strings:

	function cutVal(val,d){
		var x='100000000000000000000'.substring(0,d+1);
		return parseInt(val*x)/x;
	}

Which shows me that the Math object and using "to the power of" is not
that common :-)

<tip type="JavaScript" title="How to cut a number off after a certain
amount of decimals">
	function cutOff(val,decimals){
		return parseInt(val*Math.pow(10,decimals))/Math.pow(10,decimals);
	}
val is the number, decimals the number of decimals
	alert(cutOff(3.141,2))   => 3.14
	alert(cutOff(3.141,1))   => 3.1
	alert(cutOff(3.141,3))   => 3.141
</tip>

:-)


--
Chris Heilmann
Blog: http://www.wait-till-i.com
Writing: http://icant.co.uk/
Binaries: http://www.onlinetools.org/



More information about the thelist mailing list