28.05.2013 Views

javascript by example

javascript by example

javascript by example

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Capitolo 1<br />

}<br />

s=s.replace(/m+/,this.getMinutes());<br />

s=s.replace(/s+/,this.getSeconds());<br />

return s;<br />

Così potremmo usare:<br />

var dt = new Date();<br />

alert(dt.format("d/M/y h:m:s"));<br />

Linguaggio<br />

36 Arrotondamenti<br />

Anche l'oggetto Number si presta a interessanti estensioni, una<br />

funzione utile potrebbe essere quella degli arrotondamenti con<br />

precisione decimale:<br />

Number.prototype.round = function (precision) {<br />

}<br />

var number = this;<br />

if (precision == undefined) precision = 2;<br />

var sign = (number < 0) ? -1 : 1;<br />

var multiplier = Math.pow(10, precision);<br />

var result = Math.abs(number);<br />

result = Math.floor((result * multiplier) + .5000001) / multiplier;<br />

if (sign < 0) result = result * -1;<br />

return result;<br />

Un esempio d'uso è:<br />

n=1.5648562;<br />

document.write(n.round(3));<br />

//risultato 1,565<br />

I libri di ioPROGRAMMO/Javascript <strong>by</strong> Example 41<br />

JAVASCRIPT<br />

BY EXAMPLE

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!