JavaScript で浮動小数点数を整数に変換するにはどうすればよいですか?

Mary-Kate Olsen
リリース: 2024-10-18 06:17:30
オリジナル
882 人が閲覧しました

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);
ログイン後にコピー

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);
ログイン後にコピー

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

以上がJavaScript で浮動小数点数を整数に変換するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!