Skip to main content

parse_f64

Function parse_f64 

Source
pub fn parse_f64(literal: impl IntoBuf) -> Result<f64, NumError>
Available on crate feature num only.
Expand description

Extracts a 64-bit IEEE double-precision floating point number from any sequence of bytes that is a valid JSON number token.

When the input is a valid JSON number token, this function will return Ok if the number value in the text is within the range of an f64. If the content is within the range of an f64 but not representable due to precision limitations, Ok is returned with the nearest representable f64 value (rounded according to IEEE 754 round-to-nearest-even). For other number tokens, the result is Err(NumError::Range). For non-number tokens, the result is always Err(NumError::Format).

This is a generalized version of Content::parse_f64 that works on any IntoBuf.

§Performance considerations

  • Generally does not allocate, but will do so if the input bytes are non-contiguous.
  • Unlike integers, which have a natural finite representation, floating point numbers can conceptually have an infinite number of digits that have to be examined. Application writers should be aware of this characteristic and may wish to set and enforce length limits on number tokens before parsing the number value.

§Examples

Parse a value in the range of f64.

use bufjson::lexical::parse_f64;

assert_eq!(Ok(3.14159), parse_f64("3.14159"));

A number value that is within the range of f64 but that cannot be represented precisely is rounded to the closest representable value.

use bufjson::lexical::parse_f64;

assert_eq!(
    Ok(9007199254740994.0),                 // Got a number ending in `...4.0`.
    parse_f64("9007199254740993.1"),        // Asked for a number ending in `...3.1`.
);

A number that is outside the range of f64 cannot be parsed.

use bufjson::lexical::{NumError, parse_f64};

assert_eq!(Err(NumError::Range), parse_f64("-10e+309"));

Non-numeric values cannot be parsed.

use bufjson::lexical::{NumError, parse_f64};

assert_eq!(Err(NumError::Format), parse_f64("true"));