Die Math.trunc()
Funktion gibt den ganzzahligen Teil einer Zahl zurück, indem alle Nachkommastellen entfernt werden.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
Math.trunc(x)
Parameter
x
- Eine Zahl.
Rückgabewert
Den ganzzahligen Teil der übergebenen Zahl.
Beschreibung
Im Gegensatz zu den drei Math
Funktionen Math.floor()
, Math.ceil()
und Math.round()
arbeitet Math.trunc()
sehr einfach. Sie entfernt den Punkt und die Ziffern rechts davon, ohne zu beachten, ob es sich um eine positive oder negative Nummer handelt.
Beim übergeben eines Parameters wird dieser implizit in einen Nummern-Typ konvertiert.
Weil trunc()
eine statische Funktion von Math
ist, wird es immer als Math.trunc()
eingesetzt,
jedoch nicht als Methode eines erzeugten Math
Objektes (Math
ist kein Konstruktor).
Beispiele
Einsatz von Math.trunc()
Math.trunc(13.37); // 13
Math.trunc(42.84); // 42
Math.trunc(0.123); // 0
Math.trunc(-0.123); // -0
Math.trunc('-1.123'); // -1
Math.trunc(NaN); // NaN
Math.trunc('foo'); // NaN
Math.trunc(); // NaN
Polyfill
if(!Math.trunc) {
Math.trunc = function(v) {
v = +v;
if(!isFinite(v)) return v;
return (v - v % 1) || (v < 0 ? -0 : v === 0 ? v : 0);
// returns:
// 0 -> 0
// -0 -> -0
// 0.2 -> 0
// -0.2 -> -0
// 0.7 -> 0
// -0.7 -> -0
// Infinity -> Infinity
// -Infinity -> -Infinity
// NaN -> NaN
// null -> 0
};
}
oder:
if(!Math.trunc) {
Math.trunc = function(v) {
return v < 0 ? Math.ceil(v) : Math.floor(v);
}
}
Spezifikationen
Spezifikation | Status | Kommentar |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) Die Definition von 'Math.trunc' in dieser Spezifikation. |
Standard | Initiale Definition. |
ECMAScript (ECMA-262) Die Definition von 'Math.trunc' in dieser Spezifikation. |
Lebender Standard |
Browserkompatibilität
BCD tables only load in the browser
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.