Bagaimana Anda Boleh Menukar Nombor Terapung kepada Nombor Bulat dalam JavaScript?

Mary-Kate Olsen
Lepaskan: 2024-10-18 06:17:30
asal
881 orang telah melayarinya

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);
Salin selepas log masuk

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);
Salin selepas log masuk

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

Atas ialah kandungan terperinci Bagaimana Anda Boleh Menukar Nombor Terapung kepada Nombor Bulat dalam JavaScript?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!