Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Module « math » Python 3.11.3

Fonction trunc - module math

Signature de la fonction trunc

 def trunc(x: int|float) -> int

Description

Cette fonction renvoie la partie entière d'un nombre flottant x. Cela signifie que toutes les décimales après la virgule sont tronquées et que la valeur renvoyée est un entier.

help(math.trunc)

Truncates the Real x to the nearest Integral toward 0.

Uses the __trunc__ magic method.

Paramètre

ParamètreDescription
 x : int|float 
un nombre flottant pour lequel la partie entière doit être extraite.

Valeur de retour

La valeur de retour est de type int|float.

Elle correspond à la partie entière du nombre flottant x.

Exception

Exemple(s) de code

 1 
 2 
 3 
 4 
 5 
 6 
 7 
 8 
 9 
 10 
 11 
 12 
 13 
 14 
 15 
 16 
 17 
 18 
 19 
 20 
 21 
 22 
 23 
 24 
#!/usr/bin/python3

import math

value = 4.7
print("Math.trunc( %.1f ) == %d" % (value, math.trunc(value)))

value = 4.1
print("Math.trunc( %.1f ) == %d" % (value, math.trunc(value)))

value = 4.0
print("Math.trunc( %.1f ) == %d" % (value, math.trunc(value)))

value = 0
print("Math.trunc( %.1f ) == %d" % (value, math.trunc(value)))

value = -1.3
print("Math.trunc( %.1f ) == %d" % (value, math.trunc(value)))

value = -1.9
print("Math.trunc( %.1f ) == %d" % (value, math.trunc(value)))

value = -2
print("Math.trunc( %.1f ) == %d" % (value, math.trunc(value)))
Exemple d'utilisation de la fonction math.trunc.

Et voici les résultats produits par cet exemple.

$> python sample.py
Math.trunc( 4.7 ) == 4
Math.trunc( 4.1 ) == 4
Math.trunc( 4.0 ) == 4
Math.trunc( 0.0 ) == 0
Math.trunc( -1.3 ) == -1
Math.trunc( -1.9 ) == -1
Math.trunc( -2.0 ) == -2
$> 

Existant depuis

2.6

Voir aussi

La fonction ceil
La fonction floor
La fonction round
Les fonctions trunc, truncf et truncl en C