--- title: Math.trunc() slug: Web/JavaScript/Reference/Global_Objects/Math/trunc tags: - ECMAScript 2015 - JavaScript - Math - Méthode - Reference - polyfill translation_of: Web/JavaScript/Reference/Global_Objects/Math/trunc original_slug: Web/JavaScript/Reference/Objets_globaux/Math/trunc ---
{{JSRef}}

La fonction Math.trunc() retourne la troncature entière d'un nombre en retirant sa partie décimale.

Math.trunc(x)={xsix0xsix<0\mathtt{\operatorname{Math.trunc}(x)} = \begin{cases} \left\lfloor x \right\rfloor & \text{if} & x \geq 0 \\ \left\lceil x \right\rceil & \text{if} &x < 0 \end{cases}

{{EmbedInteractiveExample("pages/js/math-trunc.html")}}

Syntaxe

Math.trunc(x)

Paramètres

x
Un nombre.

Valeur de retour

La partie entière du nombre passé en argument.

Description

Contrairement aux autres méthodes {{jsxref("Math.floor()")}}, {{jsxref("Math.ceil()")}} et {{jsxref("Math.round()")}}, Math.trunc() fonctionne de façon très simple : la partie décimale du nombre est retirée et on conserve la partie entière (que le nombre soit positif ou négatif).

Ainsi, si l'argument est un nombre positif, Math.trunc() sera équivalent à Math.floor(), sinon Math.trunc() sera équivalent à Math.ceil().

On notera que l'argument passé à la méthode est converti en nombre de façon implicite.

trunc() est une méthode statique de Math, elle doit toujours être utilisée avec la syntaxe Math.trunc(), elle ne doit pas être utilisée comme la méthode d'un objet qui aurait été instancié (Math n'est pas un constructeur).

Exemples

Utiliser 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("toto");  // NaN
Math.trunc();        // NaN

Spécifications

Spécification État Commentaire
{{SpecName('ES2015', '#sec-math.trunc', 'Math.trunc')}} {{Spec2('ES2015')}} Première définition.
{{SpecName('ESDraft', '#sec-math.trunc', 'Math.trunc')}} {{Spec2('ESDraft')}}

Compatibilité des navigateurs

{{Compat("javascript.builtins.Math.trunc")}}

Voir aussi