dactyl

Type Alias NicePercent

Source
pub type NicePercent = NiceWrapper<SIZE>;
Expand description

NicePercent provides a quick way to convert an f32 or f64 percent — a value 0.0..=1.0 — into a formatted byte string for e.g. printing.

The precision is fixed at two decimal places (rounded at the thousandth), with output ranging from 0.00% to 100.00%.

Inputs are expected to be in 0..=1. Values less than zero are clamped to 0.00%, while values greater than 1 are clamped to 100.00%.

For other types of floats, see NiceFloat instead.

That’s it!

§Examples

use dactyl::NicePercent;
assert_eq!(NicePercent::from(0.321).as_str(), "32.10%");

§Traits

Rustdoc doesn’t do a good job at documenting type alias implementations, but NicePercent has a bunch, including:

  • AsRef<[u8]>
  • AsRef<str>
  • Borrow<[u8]>
  • Borrow<str>
  • Clone
  • Copy
  • Default
  • Deref<Target=[u8]>
  • Display
  • Eq / PartialEq
  • Hash
  • Ord / PartialOrd

Aliased Type§

struct NicePercent { /* private fields */ }

Implementations§

Source§

impl NicePercent

Source

pub const MIN: Self = _

§Minimum Value.

Zero percent.

use dactyl::NicePercent;

assert_eq!(
    NicePercent::MIN.as_str(),
    "0.00%"
);

assert_eq!(
    NicePercent::MIN,
    NicePercent::from(0_f32),
);
Source

pub const MAX: Self = _

§Maximum Value.

One hundred percent.

use dactyl::NicePercent;

assert_eq!(
    NicePercent::MAX.as_str(),
    "100.00%"
);

assert_eq!(
    NicePercent::MAX,
    NicePercent::from(1_f32),
);
Source§

impl NicePercent

Source

pub fn replace(&mut self, num: f32)

§Replace.

Reuse the backing storage behind self to hold a new nice percent.

§Examples.
use dactyl::NicePercent;

let mut num = NicePercent::from(0.85);
assert_eq!(num.as_str(), "85.00%");

num.replace(0.334);
assert_eq!(num.as_str(), "33.40%");

Trait Implementations§

Source§

impl Default for NicePercent

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<f32> for NicePercent

Source§

fn from(num: f32) -> Self

Converts to this type from the input type.
Source§

impl From<f64> for NicePercent

Source§

fn from(num: f64) -> Self

Converts to this type from the input type.
Source§

impl<T: IntDivFloat> TryFrom<(T, T)> for NicePercent

Source§

fn try_from(src: (T, T)) -> Result<Self, Self::Error>

§Percent From T/T.

This method is a shorthand that performs the (decimal) division of T1 / T2 for you, then converts the result into a NicePercent if it falls between 0.0..=1.0.

use dactyl::NicePercent;

assert_eq!(
    NicePercent::from(0.5_f64),
    NicePercent::try_from((10_u8, 20_u8)).unwrap(),
);
§Errors

Conversion will fail if the enumerator is larger than the denominator, or if the denominator is zero.

Source§

type Error = ()

The type returned in the event of a conversion error.