Created
December 8, 2008 07:53
-
-
Save yoko/33393 to your computer and use it in GitHub Desktop.
(5).toFormatString(); // => "05"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"/> | |
<title>toFormatString</title> | |
<link rel="stylesheet" href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css"/> | |
<script src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"></script> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> | |
<script src="Number.prototype.toFormatString.js"></script> | |
</head> | |
<body> | |
<h1 id="qunit-header">toFormatString</h1> | |
<h2 id="qunit-banner"></h2> | |
<h2 id="qunit-userAgent"></h2> | |
<ol id="qunit-tests"></ol> | |
<script type="text/javascript"> | |
test('String.prototype.toFormatString', function() { | |
equal(typeof '1234'.toFormatString(2), 'string', 'return string'); | |
equal(typeof '1234'.toFormatString(5), 'string', 'return string'); | |
equal('1'.toFormatString(), '01', 'default place is 2'); | |
equal('1'.toFormatString(3), '001'); | |
equal('0'.toFormatString(), '00'); | |
equal('1.1'.toFormatString(), '01.1'); | |
}); | |
test('Number.prototype.toFormatString', function() { | |
equal(typeof (1234).toFormatString(2), 'string', 'return string'); | |
equal(typeof (1234).toFormatString(5), 'string', 'return string'); | |
equal((1).toFormatString(), '01', 'default place is 2'); | |
equal((1).toFormatString(3), '001'); | |
equal((0).toFormatString(), '00'); | |
equal('1.1'.toFormatString(), '01.1'); | |
}); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Number.prototype.toFormatString = function(place) { | |
return this.toString().toFormatString(place); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.toFormatString = function(place) { | |
place = place || 2; | |
var str = this.toString(); | |
var n = str.split('.')[0].length; | |
while (n++ < place) str = '0'+str; | |
return str; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment