Converting a float to an integer in JavaScript is a common task for rounding numeric values. Here are the different methods you can use to perform this conversion efficiently, without relying on string conversion techniques.
Truncation
Truncation rounds a float towards negative infinity, discarding any fractional part. This can be achieved using the Math.floor() method:
<code class="javascript">var intvalue = Math.floor(floatvalue);</code>
Rounding
Rounding rounds a float to the nearest integer. If the fractional part is exactly 0.5, the value is rounded to the nearest even integer. The Math.round() method can be used for this purpose:
<code class="javascript">var intvalue = Math.round(floatvalue);</code>
Ceil
Ceil rounds a float upwards to the nearest integer. This is similar to rounding, except that it always rounds up, regardless of the fractional part. The Math.ceil() method can be used for this:
<code class="javascript">var intvalue = Math.ceil(floatvalue);</code>
ECMAScript 6's Math.trunc()
The ECMAScript 6 standard introduced a new method, Math.trunc(), which explicitly truncates a float to an integer without rounding:
<code class="javascript">var intvalue = Math.trunc(floatvalue);</code>
Bitwise Operators
Bitwise operators can also be used to truncate a float in JavaScript:
Examples
Here are some examples of converting floats to integers using different methods:
Method | Positive Float (5.5) | Positive Large Float | Negative Float (-5.5) | Large Negative Float |
---|---|---|---|---|
Math.floor | 5 | 900719925474099 | -6 | -900719925474100 |
Math.ceil | 6 | 900719925474100 | -5 | -900719925474099 |
Math.round | 6 | 900719925474100 | -6 | -900719925474100 |
Math.trunc | 5 | 900719925474099 | -5 | -900719925474099 |
~~ | 5 | 858993459 | -5 | -858993459 |
Math Object Reference
For more information on the Math object and its methods, refer to the [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math).
Das obige ist der detaillierte Inhalt vonWie konvertiere ich in JavaScript effektiv eine Gleitkommazahl in eine Ganzzahl?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!