var r = (Math.random() * 200) - 100;
? , , "":
var n = r + (r < 0 ? -0.5 : 0.5) | 0;
| 0 | 0 - js, "" ( ) , .
, ( Math.floor), , , Math.floor(-3.2) -4.
You can even do something similar to @ Balan's answer (I like this one and the one below, but I feel that it is, otherwise the ternary operator will be faster to the touch - although I'm probably mistaken because the libraries Mathwere very quickly)
var n = (r + Math.sign(r) / 2) | 0;
probably the fastest, most elegant way:
var n = Math.floor(r + 0.5);
example:
var body = document.getElementById("myTable").children[1];
var i, iMax = 100, r, tr, td;
for (i = 0; i < iMax; i++) {
r = Math.random() * 200 - 100;
tr = document.createElement("tr");
td = document.createElement("td");
td.innerHTML = r;
tr.appendChild(td);
td = document.createElement("td");
td.innerHTML = (r + Math.sign(r) / 2) | 0;
tr.appendChild(td);
body.appendChild(tr);
}
#myTable {
min-width: 250px;
}
<table id="myTable">
<thead>
<tr>
<th>float</th>
<th>round</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Run codeHide result source
share