Skip to main content

set_str

Function set_str 

Source
pub fn set_str(
    s: &str,
    base: u8,
    prec: u64,
    rm: RoundingMode,
) -> Option<(Float, Ordering)>
Expand description

Converts a string to a Float, requiring that the whole string be a valid number.

This is strtofr with the trailing text disallowed: it returns the value and the Ordering of that value against the string’s exact value, or None if the string is empty or is not entirely consumed. See strtofr for the grammar, which is MPFR’s rather than Malachite’s.

Note that trailing whitespace is trailing text, and so is rejected, even though leading whitespace is skipped.

§Worst-case complexity

$T(n) = O(n (\log n)^2 \log\log n)$

$M(n) = O(n \log n)$

where $T$ is time, $M$ is additional memory, and $n$ is max(s.len(), prec).

§Panics

Panics if base is 1 or greater than 62, if prec is zero, or if rm is Exact but the string’s value is not exactly representable with prec bits.

§Examples

use core::cmp::Ordering::*;
use malachite_base::rounding_modes::RoundingMode::*;
use malachite_float::float::conversion::string::strtofr::set_str;

let s = |s, base, prec, rm| set_str(s, base, prec, rm).map(|(x, o)| (x.to_string(), o));

assert_eq!(
    s("1.5", 10, 10, Nearest),
    Some(("1.5000".to_string(), Equal))
);
assert_eq!(
    s("0.1", 10, 4, Nearest),
    Some(("0.102".to_string(), Greater))
);

// Trailing text that `strtofr` would simply stop at is rejected here.
assert_eq!(s("1.5abc", 10, 10, Nearest), None);
assert_eq!(s("1.5 ", 10, 10, Nearest), None);
assert_eq!(s("", 10, 10, Nearest), None);

This is mpfr_set_str from set_str.c, MPFR 4.3.0. MPFR’s version reports only success or failure, discarding the ternary value; this one returns it.