Maison > interface Web > js tutoriel > le corps du texte

Comment convertir des nombres flottants en nombres entiers en JavaScript ?

Mary-Kate Olsen
Libérer: 2024-10-18 06:17:30
original
881 Les gens l'ont consulté

How Can You Convert Float Numbers to Whole Numbers in JavaScript?

Converting Float Numbers to Whole Numbers in JavaScript

Converting float numbers to whole numbers is a common task in JavaScript. There are two primary methods to accomplish this: truncation and rounding.

Truncation with Math.floor()

Truncation involves removing the decimal portion of a number, resulting in the nearest integer towards negative infinity. This is achieved using the Math.floor() function:

var intvalue = Math.floor(floatvalue);
Copier après la connexion

Rounding with Math.ceil() and Math.round()

Rounding can be performed in two ways:

  • Math.ceil(): Rounds the number up to the nearest integer towards positive infinity.
  • Math.round(): Similar to Math.ceil(), but rounds to the nearest integer, even if it's towards negative infinity when the fractional part is exactly 0.5.

The code below demonstrates these methods:

var intvalue = Math.ceil(floatvalue); 
var intvalue = Math.round(floatvalue);
Copier après la connexion

Additional Considerations

  • Math.trunc(): Available in ECMAScript 6, this function specifically truncates the number without rounding.
  • Other Methods: Bit manipulation operators like ~, >>, and >>> can also be used to convert floats to integers, although they may not be as efficient.

Examples

The following table illustrates the different conversion methods with various input values:

Value Math.floor() Math.ceil() Math.round()
Positive (Less than 3.5) Truncated Rounded up Rounded up
Positive (Greater than or equal to 3.5) Truncated Rounded up Rounded up
Negative (Greater than -3.5) Rounded up Truncated Truncated
Negative (Less than or equal to -3.5) Rounded up Truncated Rounded down

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!