JavaScript DataView getFloat32() Method



The JavaScript DataView getFloat32() method is used to retrieve 4-byte floating point numbers starting at the specified byte offset of this data view and decodes them into 32-bit floating point numbers. You can fetch multiple byte values from any offset within bounds.

This method throws a 'RangeError' exception if the value of the byte offset parameter falls outside the bounds of this data view.

Syntax

Following is the syntax of the JavaScript DataView getFloat32() method −

getFloat32(byteOffset, littleEndian)

Parameters

This method accepts two parameters named 'byteOffset' and 'littleEndian', which are described below −

  • byteOffset − The position in the DataView from which to read the data.
  • littleEndian (optional) − It indicates whether the data is stored in little-or-big endian.

Return value

This method returns an integer within the range of -3.4e38 to 3.4e38.

Example 1

The following is the basic example of the JavaScript DataView getFloat32() method.

Open Compiler
<html> <body> <script> const buffer = new ArrayBuffer(16); const data_view = new DataView(buffer); const byteOffset = 0; const value = Math.PI; document.write("The byte offset: ", byteOffset); document.write("<br>Value: ", value); //storing the value data_view.setFloat32(byteOffset, value); document.write("<br>The stored value: ", data_view.getFloat32(byteOffset)); </script> </body> </html>

Output

The above program returns the stored value as "3.1415927410125732".

The byte offset: 0
Value: 3.141592653589793
The stored value: 3.1415927410125732

Example 2

If the byteOffset parameter value falls outside the bounds of this data view, it will throw a 'RangeError' exception.

Open Compiler
<html> <body> <script> const buffer = new ArrayBuffer(16); const data_view = new DataView(buffer); const byteOffset = 1; const value = 3.445323412; document.write("The byte offset: ", byteOffset); document.write("<br>Value: ", value); //storing the value data_view.setFloat32(byteOffset, value); try { document.write("<br>The stored value: ", data_view.getFloat32(-1)); } catch (error) { document.write("<br>", error); } </script> </body> </html>

Output

After executing the above program, it will throw an exception as −

The byte offset: 1
Value: 3.445323412
RangeError: Offset is outside the bounds of the DataView
Advertisements