DE
JavaScript - Math.trunc() Methode - Beispiel
3 points
Die Math.trunc()
Methode gibt einen ganzzahligen Teil einer Zahl zurück.
xxxxxxxxxx
1
console.log( Math.trunc( 5 )); // 5
2
console.log( Math.trunc( 3.14 )); // 3
3
console.log( Math.trunc( -3.14 )); // -3
4
console.log( Math.trunc( 0.123 )); // 0
5
console.log( Math.trunc( -0.123 )); // -0
6
7
console.log( Math.trunc( '+3.14' ) ); // 3.14
8
console.log( Math.trunc( '-3.14' ) ); // -3.14
9
console.log( Math.trunc( NaN ) ); // NaN
10
console.log( Math.trunc( 'foo' ) ); // NaN
11
12
console.log( Math.trunc() ); // NaN
Syntax | Math.trunc(number) |
Parameter | number - Ganzzahl-oder Gleitkommazahlwert (primitiver Wert). |
Ergebnis |
Ganzzahliger Teil des Wenn die Wenn Wenn |
Beschreibung |
|
Dieses Beispiel zeigt eine Polyfill-Lösung für das Fehlen der Methode.
xxxxxxxxxx
1
if (Math.trunc == null) {
2
Math.trunc = function (v) {
3
return v < 0 ? Math.ceil(v) : Math.floor(v);
4
};
5
}
6
7
// Anwendungsbeispiel:
8
9
console.log( Math.trunc( 5 )); // 5
10
console.log( Math.trunc( 3.14 )); // 3
11
console.log( Math.trunc( -3.14 )); // -3
12
console.log( Math.trunc( 0.123 )); // 0
13
console.log( Math.trunc( -0.123 )); // -0