pub struct WriteFloatOptions { /* private fields */ }
write-floats
only.Expand description
Options to customize writing floats.
This enables extensive control over how the float is written, from control characters like the decimal point, to the use of exponent notation, and the number of significant digits.
§Examples
Writing a simple float with custom special strings and formatting integral floats as integers can be done as:
use core::str;
use lexical_write_float::{Options, ToLexical, ToLexicalWithOptions};
use lexical_write_float::format::STANDARD;
const OPTS: Options = Options::builder()
.trim_floats(true)
.nan_string(Some(b"NaN"))
.inf_string(Some(b"Inf"))
.build_strict();
const SIZE: usize = OPTS.buffer_size_const::<f64, STANDARD>();
let mut buffer = [0u8; SIZE];
// trim floats
let digits = 12345.0f64.to_lexical_with_options::<STANDARD>(&mut buffer, &OPTS);
assert_eq!(str::from_utf8(digits), Ok("12345"));
// don't trim floats
let digits = 12345.0f64.to_lexical(&mut buffer);
assert_eq!(str::from_utf8(digits), Ok("12345.0"));
Implementations§
Source§impl Options
impl Options
Sourcepub const fn from_radix(radix: u8) -> Options
pub const fn from_radix(radix: u8) -> Options
Create the default options for a given radix.
This function will never fail even if the radix is invalid. It is up to
the caller to ensure the format is valid using
Options::is_valid
. Only radixes from 2
to 36
should be used.
Sourcepub const fn buffer_size_const<T, const FORMAT: u128>(&self) -> usizewhere
T: FormattedSize,
pub const fn buffer_size_const<T, const FORMAT: u128>(&self) -> usizewhere
T: FormattedSize,
Get an upper bound on the required buffer size.
This is used when custom formatting options, such as significant
digits specifiers or custom exponent breaks, are used, which
can lead to more or less significant digits being written than
expected. If using the default formatting options, then this will
always be FORMATTED_SIZE
or
FORMATTED_SIZE_DECIMAL
,
depending on the radix.
§Examples
use core::{num, str};
use lexical_write_float::{FormattedSize, Options, ToLexicalWithOptions};
use lexical_write_float::format::STANDARD;
const DEFAULT: Options = Options::builder()
// require at least 3 significant digits, so `0.01` would be `"0.0100"`.
.min_significant_digits(num::NonZeroUsize::new(3))
// allow at most 5 significant digits, so `1.23456` would be `"1.2346"`.
.max_significant_digits(num::NonZeroUsize::new(5))
// build our format, erroring if it's invalid
.build_strict();
assert_eq!(DEFAULT.buffer_size_const::<f64, STANDARD>(), f64::FORMATTED_SIZE_DECIMAL);
const CUSTOM: Options = Options::builder()
// require at least 300 significant digits.
.min_significant_digits(num::NonZeroUsize::new(300))
// allow at most 500 significant digits.
.max_significant_digits(num::NonZeroUsize::new(500))
// only write values with magnitude above 1e300 in exponent notation
.positive_exponent_break(num::NonZeroI32::new(300))
// only write values with magnitude below 1e-300 in exponent notation
.negative_exponent_break(num::NonZeroI32::new(-300))
.build_strict();
// 300 for the significant digits (500 is never reachable), 300 extra
// due to the exponent breakoff, 1 for the sign, 1 for the decimal point
// in all cases, this is enough including the exponent character and sign.
assert_eq!(CUSTOM.buffer_size_const::<f64, STANDARD>(), 602);
// now, write out value to bytes
const SIZE: usize = CUSTOM.buffer_size_const::<f64, STANDARD>();
let mut buffer = [0u8; SIZE];
let value = 1.23456e-299f64;
let digits = value.to_lexical_with_options::<STANDARD>(&mut buffer, &CUSTOM);
// validate our printed digits. 600!
assert_eq!(digits.len(), 600);
assert!(!digits.contains(&b'e') && !digits.contains(&b'E'));
assert!(digits.starts_with(b"0.000000000000000000000000"));
// validate the round-trip
assert_eq!(str::from_utf8(digits).unwrap().parse::<f64>(), Ok(value));
// let's serialize a slightly smaller value
let value = 1.23456e-301f64;
let digits = value.to_lexical_with_options::<STANDARD>(&mut buffer, &CUSTOM);
assert_eq!(digits.len(), 306);
let digits = value.to_lexical_with_options::<STANDARD>(&mut buffer, &CUSTOM);
Sourcepub const fn max_significant_digits(&self) -> Option<NonZero<usize>>
pub const fn max_significant_digits(&self) -> Option<NonZero<usize>>
Get the maximum number of significant digits to write.
This limits the total number of written digits, truncating based
on the round_mode
if more digits would normally be written. If
no value is provided, then it writes as many digits as required to
create an unambiguous representation of the float.
§Examples
use core::num::NonZeroUsize;
use lexical_write_float::Options;
const MAX_DIGITS: Option<NonZeroUsize> = NonZeroUsize::new(300);
const OPTIONS: Options = Options::builder()
.max_significant_digits(MAX_DIGITS)
.build_strict();
assert_eq!(OPTIONS.max_significant_digits(), MAX_DIGITS);
Sourcepub const fn min_significant_digits(&self) -> Option<NonZero<usize>>
pub const fn min_significant_digits(&self) -> Option<NonZero<usize>>
Get the minimum number of significant digits to write.
If more digits exist, such as writing “1.2” with a minimum of 5
significant digits, then 0
s are appended to the end of the digits.
If no value is provided, then it writes as few digits as required to
create an unambiguous representation of the float.
§Examples
use core::num::NonZeroUsize;
use lexical_write_float::Options;
const MIN_DIGITS: Option<NonZeroUsize> = NonZeroUsize::new(10);
const OPTIONS: Options = Options::builder()
.min_significant_digits(MIN_DIGITS)
.build_strict();
assert_eq!(OPTIONS.min_significant_digits(), MIN_DIGITS);
Sourcepub const fn positive_exponent_break(&self) -> Option<NonZero<i32>>
pub const fn positive_exponent_break(&self) -> Option<NonZero<i32>>
Get the maximum exponent prior to using scientific notation.
If the value is set to 300
, then any value with magnitude >= 1e300
(for base 10) will be writen in exponent notation, while any lower
value will be written in decimal form. If no value is provided, for
decimal floats, this defaults to 9
.
§Examples
use core::num::NonZeroI32;
use lexical_write_float::Options;
const POS_BREAK: Option<NonZeroI32> = NonZeroI32::new(3);
const OPTIONS: Options = Options::builder()
.positive_exponent_break(POS_BREAK)
.build_strict();
assert_eq!(OPTIONS.positive_exponent_break(), POS_BREAK);
Sourcepub const fn negative_exponent_break(&self) -> Option<NonZero<i32>>
pub const fn negative_exponent_break(&self) -> Option<NonZero<i32>>
Get the minimum exponent prior to using scientific notation.
If the value is set to -300
, then any value with magnitude < 1e-300
(for base 10) will be writen in exponent notation, while any larger
value will be written in decimal form. If no value is provided, for
decimal floats, this defaults to -5
.
§Examples
use core::num::NonZeroI32;
use lexical_write_float::Options;
const NEG_BREAK: Option<NonZeroI32> = NonZeroI32::new(-3);
const OPTIONS: Options = Options::builder()
.negative_exponent_break(NEG_BREAK)
.build_strict();
assert_eq!(OPTIONS.negative_exponent_break(), NEG_BREAK);
Sourcepub const fn round_mode(&self) -> RoundMode
pub const fn round_mode(&self) -> RoundMode
Get the rounding mode for writing digits with precision control.
For example, writing 1.23456
with 5 significant digits with
RoundMode::Round
would produce "1.2346"
while
RoundMode::Truncate
would produce "1.2345"
. Defaults to
RoundMode::Round
.
§Examples
use lexical_write_float::{Options, RoundMode};
const OPTIONS: Options = Options::builder()
.round_mode(RoundMode::Truncate)
.build_strict();
assert_eq!(OPTIONS.round_mode(), RoundMode::Truncate);
Sourcepub const fn trim_floats(&self) -> bool
pub const fn trim_floats(&self) -> bool
Get if we should trim a trailing ".0"
from integral floats.
If used in conjunction with min_significant_digits
,
this will still trim all the significant digits if an integral
value is provided. Defaults to false
.
§Examples
use lexical_write_float::Options;
const OPTIONS: Options = Options::builder()
.trim_floats(true)
.build_strict();
assert_eq!(OPTIONS.trim_floats(), true);
Sourcepub const fn exponent(&self) -> u8
pub const fn exponent(&self) -> u8
Get the character to designate the exponent component of a float.
Any non-control character is valid, but \t
to \r
are also valid.
The full range is [0x09, 0x0D]
and [0x20, 0x7F]
. Defaults to e
.
§Examples
use lexical_write_float::Options;
const OPTIONS: Options = Options::builder()
.exponent(b'^')
.build_strict();
assert_eq!(OPTIONS.exponent(), b'^');
Sourcepub const fn decimal_point(&self) -> u8
pub const fn decimal_point(&self) -> u8
Get the character to separate the integer from the fraction components.
Any non-control character is valid, but \t
to \r
are also valid.
The full range is [0x09, 0x0D]
and [0x20, 0x7F]
. Defaults to .
.
§Examples
use lexical_write_float::Options;
const OPTIONS: Options = Options::builder()
.exponent(b',')
.build_strict();
assert_eq!(OPTIONS.exponent(), b',');
Sourcepub const fn nan_string(&self) -> Option<&'static [u8]>
pub const fn nan_string(&self) -> Option<&'static [u8]>
Get the string representation for NaN
.
The first character must start with N
or n
and all characters must
be valid ASCII letters (A-Z
or a-z
). If set to None
, then writing
NaN
returns an error. Defaults to NaN
.
§Examples
use lexical_write_float::Options;
const OPTIONS: Options = Options::builder()
.nan_string(Some(b"nan"))
.build_strict();
assert_eq!(OPTIONS.nan_string(), Some(b"nan".as_ref()));
Sourcepub const fn inf_string(&self) -> Option<&'static [u8]>
pub const fn inf_string(&self) -> Option<&'static [u8]>
Get the string representation for Infinity
.
The first character must start with I
or i
and all characters must
be valid ASCII letters (A-Z
or a-z
). If set to None
, then writing
Infinity
returns an error. Defaults to inf
.
§Examples
use lexical_write_float::Options;
const OPTIONS: Options = Options::builder()
.inf_string(Some(b"infinity"))
.build_strict();
assert_eq!(OPTIONS.inf_string(), Some(b"infinity".as_ref()));
Sourcepub const fn infinity_string(&self) -> Option<&'static [u8]>
pub const fn infinity_string(&self) -> Option<&'static [u8]>
Get the string representation for Infinity
. Alias for inf_string
.
The first character must start with I
or i
and all characters must
be valid ASCII letters (A-Z
or a-z
). If set to None
, then writing
Infinity
returns an error. Defaults to inf
.
§Examples
use lexical_write_float::Options;
const OPTIONS: Options = Options::builder()
.infinity_string(Some(b"infinity"))
.build_strict();
assert_eq!(OPTIONS.infinity_string(), Some(b"infinity".as_ref()));
Sourcepub fn set_max_significant_digits(
&mut self,
max_significant_digits: Option<NonZero<usize>>,
)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_max_significant_digits( &mut self, max_significant_digits: Option<NonZero<usize>>, )
OptionsBuilder
instead. Will be removed in 2.0.Set the maximum number of significant digits to write.
This limits the total number of written digits, truncating based
on the round_mode
if more digits would normally be written.
§Panics
This will panic when writing the float if the value is smaller than
min_significant_digits
.
Sourcepub fn set_min_significant_digits(
&mut self,
min_significant_digits: Option<NonZero<usize>>,
)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_min_significant_digits( &mut self, min_significant_digits: Option<NonZero<usize>>, )
OptionsBuilder
instead. Will be removed in 2.0.Set the minimum number of significant digits to write.
If more digits exist, such as writing “1.2” with a minimum of 5
significant digits, then 0
s are appended to the end of the digits.
§Panics
This will panic when writing the float if the value is larger than
max_significant_digits
.
Sourcepub fn set_positive_exponent_break(
&mut self,
positive_exponent_break: Option<NonZero<i32>>,
)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_positive_exponent_break( &mut self, positive_exponent_break: Option<NonZero<i32>>, )
OptionsBuilder
instead. Will be removed in 2.0.Set the maximum exponent prior to using scientific notation.
If the value is set to 300
, then any value with magnitude >= 1e300
(for base 10) will be writen in exponent notation, while any lower
value will be written in decimal form.
Sourcepub fn set_negative_exponent_break(
&mut self,
negative_exponent_break: Option<NonZero<i32>>,
)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_negative_exponent_break( &mut self, negative_exponent_break: Option<NonZero<i32>>, )
OptionsBuilder
instead. Will be removed in 2.0.Set the minimum exponent prior to using scientific notation.
If the value is set to -300
, then any value with magnitude < 1e-300
(for base 10) will be writen in exponent notation, while any larger
value will be written in decimal form.
Sourcepub fn set_round_mode(&mut self, round_mode: RoundMode)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_round_mode(&mut self, round_mode: RoundMode)
OptionsBuilder
instead. Will be removed in 2.0.Set the rounding mode for writing digits with precision control.
For example, writing 1.23456
with 5 significant digits with
RoundMode::Round
would produce "1.2346"
while
RoundMode::Truncate
would produce "1.2345"
.
Sourcepub fn set_trim_floats(&mut self, trim_floats: bool)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_trim_floats(&mut self, trim_floats: bool)
OptionsBuilder
instead. Will be removed in 2.0.Set if we should trim a trailing ".0"
from integral floats.
If used in conjunction with min_significant_digits
,
this will still trim all the significant digits if an integral
value is provided.
Sourcepub fn set_exponent(&mut self, exponent: u8)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_exponent(&mut self, exponent: u8)
OptionsBuilder
instead. Will be removed in 2.0.Set the character to designate the exponent component of a float.
§Safety
Always safe, but may produce invalid output if the exponent is not a valid ASCII character.
Sourcepub fn set_decimal_point(&mut self, decimal_point: u8)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_decimal_point(&mut self, decimal_point: u8)
OptionsBuilder
instead. Will be removed in 2.0.Set the character to separate the integer from the fraction components.
§Safety
Always safe, but may produce invalid output if the decimal point is not a valid ASCII character.
Sourcepub fn set_nan_string(&mut self, nan_string: Option<&'static [u8]>)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_nan_string(&mut self, nan_string: Option<&'static [u8]>)
OptionsBuilder
instead. Will be removed in 2.0.Set the string representation for NaN
.
Panics
Setting a value too large may cause a panic even if FORMATTED_SIZE
elements are provided.
Sourcepub fn set_inf_string(&mut self, inf_string: Option<&'static [u8]>)
👎Deprecated: Options should be treated as immutable, use OptionsBuilder
instead. Will be removed in 2.0.
pub fn set_inf_string(&mut self, inf_string: Option<&'static [u8]>)
OptionsBuilder
instead. Will be removed in 2.0.Set the short string representation for Infinity
Panics
Setting a value too large may cause a panic even if FORMATTED_SIZE
elements are provided.
Sourcepub const fn builder() -> OptionsBuilder
pub const fn builder() -> OptionsBuilder
Get OptionsBuilder
as a static function.
Sourcepub const fn rebuild(&self) -> OptionsBuilder
pub const fn rebuild(&self) -> OptionsBuilder
Create OptionsBuilder
using existing values.
Trait Implementations§
Source§impl WriteOptions for Options
impl WriteOptions for Options
Source§fn buffer_size<T, const FORMAT: u128>(&self) -> usizewhere
T: FormattedSize,
👎Deprecated: Use buffer_size_const
instead. Will be removed in 2.0.
fn buffer_size<T, const FORMAT: u128>(&self) -> usizewhere
T: FormattedSize,
buffer_size_const
instead. Will be removed in 2.0.Get an upper bound on the required buffer size.
This method is soft-deprecated and meant for internal use.
You should always use buffer_size_const
so you can get
the required buffer size at compile time to determine the
buffer size required.
This is used when custom formatting options, such as significant
digits specifiers or custom exponent breaks, are used, which
can lead to more or less significant digits being written than
expected. If using the default formatting options, then this will
always be FORMATTED_SIZE
or
FORMATTED_SIZE_DECIMAL
,
depending on the radix.