logo

Comment arrondir un nombre en Python

Python fournit la fonction intégrée round(), qui arrondissait un nombre à un nombre donné de chiffres. Il prend les deux arguments, le premier est n, le second est n chiffres, puis il renvoie le nombre n après l'avoir arrondi à ndigits. Par défaut, il arrondit le nombre n à l'entier le plus proche.

Par exemple - Si nous voulons arrondir un nombre, supposons 7,5. Il sera arrondi à l'entier le plus proche soit 7. Toutefois, le nombre 7,56 sera arrondi à 7,5 d'une place pour donner.

La fonction round() est essentielle lorsque vous travaillez avec un nombre de flottants pouvant avoir plusieurs décimales. La fonction round() rend facile et simple. La syntaxe est donnée ci-dessous.

Syntaxe:

 round(number, number of digits) 

Les paramètres sont -

  • nombre - Il représente le nombre donné à arrondir.
  • nombre de chiffres (Facultatif) - Il représente le nombre de chiffres auquel le nombre donné doit être arrondi.

Comprenons l'exemple suivant -

Exemple -

 print(round(15)) # For floating point print(round(25.8)) print(round(25.4)) 

Sortir:

liste des polices Gimp
 15 26 25 

Maintenant, le deuxième paramètre est utilisé.

Exemple -

 print(round(25.4654, 2)) # when the (ndigit+1)th digit is &gt;=5 print(round(25.4276, 3)) # when the (ndigit+1)th digit is <5 print(round(25.4173, 2)) < pre> <p> <strong>Output:</strong> </p> <pre> 25.47 25.428 25.42 </pre> <h3>The real-life example of the round() function</h3> <p>The round() function is most useful while changing fractions to decimals. We generally get the number of a decimal points such as if we do 1/3 then we get 0.333333334, but we use either two or three digits to the right of the decimal points. Let&apos;s understand the following example.</p> <p> <strong>Example -</strong> </p> <pre> x = 1/6 print(x) print(round(x, 2)) </pre> <p> <strong>Output:</strong> </p> <pre> 0.16666666666666666 0.17 </pre> <p>Another example</p> <p> <strong>Example -</strong> </p> <pre> print(round(5.5)) print(round(5)) print(round(6.5)) </pre> <p> <strong>Output:</strong> </p> <pre> 6 5 6 </pre> <p>The <strong>round()</strong> function rounds 5.5 up to 6 and 6.5 down to 6. This is not a bug, the <strong>round()</strong> behaves like this way.</p> <hr></5>

L'exemple réel de la fonction round()

La fonction round() est la plus utile lors de la conversion de fractions en décimales. Nous obtenons généralement le nombre de points décimaux, par exemple si nous faisons 1/3, nous obtenons 0,333333334, mais nous utilisons deux ou trois chiffres à droite des points décimaux. Comprenons l'exemple suivant.

Exemple -

combien de semaines y a-t-il dans un mois
 x = 1/6 print(x) print(round(x, 2)) 

Sortir:

 0.16666666666666666 0.17 

Un autre exemple

Exemple -

 print(round(5.5)) print(round(5)) print(round(6.5)) 

Sortir:

 6 5 6 

Le rond() la fonction arrondit 5,5 à 6 et 6,5 à 6. Ce n'est pas un bug, le rond() se comporte ainsi.