Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

floating point - Difference between floats and ints in Javascript?

I'm looking through some of the code from the Google Closure Library and I found this line:

var isNegative = number < 0.0 || number == 0.0 && 1 / number < 0.0;

I've figured that the reason for such an initially strange looking sign-check is to identify -0 as negative, but is there any reason to use 0.0 instead of 0?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

(A lot has changed since 2011 when this answer was posted - see updates below)

2019-June Update

BigInt has been out in V8 (Node.js and Chromium-based browsers) since May 2018. It should land in Firefox 68 - see the SpiderMonkey ticket. Also implemented in WebKit.

BigDecimal hasn't been implemented by any engine yet. Look at alternative library.

2015 Update

It's been over 4 years since I wrote this answer and the situation is much more complicated now.

Now we have:

Soon we'll have:

It means that the number of numeric types available in JavaScript will grow from just one:

to at least the following in WebAssembly:

  • 8-bit integer (signed and unsigned)
  • 16-bit integer (signed and unsigned)
  • 32-bit integer (signed and unsigned)
  • 64-bit integer (signed and unsigned)
  • 32-bit floating point
  • 64-bit floating point

(Technically the internal representations of all integer types are unsigned at the lowest level but different operators can treat them as signed or unsigned, like e.g. int32.sdiv vs. int32.udiv etc.)

Those are available in typed arrays:

  • 8-bit two's complement signed integer
  • 8-bit unsigned integer
  • 8-bit unsigned integer (clamped)
  • 16-bit two's complement signed integer
  • 16-bit unsigned integer
  • 32-bit two's complement signed integer
  • 32-bit unsigned integer
  • 32-bit IEEE floating point number
  • 64-bit IEEE floating point number

asm.js defines the following numeric types:

  • int
  • signed
  • unsigned
  • intish
  • fixnum
  • double
  • double?
  • float
  • float?
  • floatish

Original 2011 answer

There is only one number type in JavaScript – the IEEE 754 double precision floating-point number.

See those questions for some consequences of that fact:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...