JavaScript DHTML/Development/Number Format

Материал из Web эксперт
Перейти к: навигация, поиск

A Generic Number-Formatting Routine

<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>
<H1>How to Make Money</H1>
<FORM>
Enter a positive floating-point value or arithmetic expression to be converted to a currency format:<P>
<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>



Number format Demo

<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>
<font face="arial" size="2">
<script>
var doc=document;
f=dynapi.functions;
doc.write("formatNumber: "+f.formatNumber("-5353535.56363","$#,##0.00")+"<br><br>");
</script>
</font>
</body>
</html>


<A href="http://www.wbex.ru/Code/JavaScriptDownload/dynapi.zip">dynapi.zip( 791 k)</a>


Number format, round and total

<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 >
<B> Two Decimal Places </B>
<BR>
0.00 is 
<script LANUAGE="JavaScript1.1">
document.write(twoPlaces(0.00));
</script>
<BR>
.10 is 
<script LANUAGE="JavaScript1.1">
document.write(twoPlaces(.10));
</script>
<BR>
1 is 
<script LANUAGE="JavaScript1.1">
document.write(twoPlaces(1))
</script>
<BR>
.-530 is 
<script LANUAGE="JavaScript1.1">
document.write(twoPlaces(-.530) )
</script>
<BR><BR> 
51.02 - 3.8 = 
<B>
<script LANUAGE="JavaScript1.1">
document.write(round(totals(51.02) - totals(3.80) ));
</script>
</BODY>
</HTML>