Heim > Web-Frontend > js-Tutorial > Hauptteil

Wie können Sie Float-Zahlen in JavaScript in ganze Zahlen umwandeln?

Mary-Kate Olsen
Freigeben: 2024-10-18 06:17:30
Original
881 Leute haben es durchsucht

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);
Nach dem Login kopieren

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);
Nach dem Login kopieren

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

Das obige ist der detaillierte Inhalt vonWie können Sie Float-Zahlen in JavaScript in ganze Zahlen umwandeln?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!