JavaScript DHTML/Development/Number Format
Содержание
A Generic Number-Formatting Routine
<source lang="html4strict">
<HTML> <HEAD> <TITLE>Number Formatting</TITLE> <SCRIPT LANGUAGE="JavaScript"> // generic positive number decimal formatting function function format (expr, decplaces) {
var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces)) while (str.length <= decplaces) { str = "0" + str } var decpoint = str.length - decplaces return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
} function dollarize (expr) {
return "$" + format(expr,2)
} </SCRIPT> </HEAD> <BODY>
How to Make Money
<FORM>
Enter a positive floating-point value or arithmetic expression to be converted to a currency format:<INPUT TYPE="text" NAME="entry" VALUE="1/3"> <INPUT TYPE="button" VALUE="Dollars and Cents" onClick="this.form.result.value=dollarize(this.form.entry.value)"> <INPUT TYPE="text" NAME="result"> </FORM> </BODY> </HTML> </source>
Number format Demo
<source lang="html4strict">
<html>
<head>
<title>DynAPI Examples - Functions</title>
<script language="JavaScript" src="./dynapisrc/dynapi.js"></script>
<script language="Javascript">
dynapi.library.setPath("./dynapisrc/");
dynapi.library.include("dynapi.library");
dynapi.library.include("dynapi.functions");
dynapi.library.include("dynapi.api");
</script>
</head>
<body>
<script>
var doc=document;
f=dynapi.functions;
doc.write("formatNumber: "+f.formatNumber("-5353535.56363","$#,##0.00")+"
");
</script>
</body>
</html>
</source>
<A href="http://www.wbex.ru/Code/JavaScriptDownload/dynapi.zip">dynapi.zip( 791 k)</a>
Number format, round and total
<source lang="html4strict">
<HTML> <HEAD> <SCRIPT LANUAGE="JavaScript1.1"> // returns the amount in the .99 format function twoPlaces(amount) {
return (amount == Math.floor(amount)) ? amount + ".00" : ((amount*10 == Math.floor(amount*10)) ? amount + "0" : amount);
}
// rounds number to X decimal places, defaults to 2
function round(number,X) {
X = (!X ? 2 : X); return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
} function totals(num) {
return twoPlaces(Math.floor((num - 0) * 100) / 100);
}
</SCRIPT>
</HEAD>
<BODY >
Two Decimal Places
0.00 is
<script LANUAGE="JavaScript1.1">
document.write(twoPlaces(0.00));
</script>
.10 is
<script LANUAGE="JavaScript1.1">
document.write(twoPlaces(.10));
</script>
1 is
<script LANUAGE="JavaScript1.1">
document.write(twoPlaces(1))
</script>
.-530 is
<script LANUAGE="JavaScript1.1">
document.write(twoPlaces(-.530) )
</script>
51.02 - 3.8 =
<script LANUAGE="JavaScript1.1">
document.write(round(totals(51.02) - totals(3.80) ));
</script>
</BODY>
</HTML>
</source>