MCPcopy Index your code
hub / github.com/RustPython/RustPython / format_float

Method format_float

crates/common/src/format.rs:683–757  ·  view source on GitHub ↗
(&self, num: f64)

Source from the content-addressed store, hash-verified

681 }
682
683 pub fn format_float(&self, num: f64) -> Result<String, FormatSpecError> {
684 self.validate_format(FormatType::FixedPoint(Case::Lower))?;
685 let precision = self.precision.unwrap_or(6);
686 let magnitude = num.abs();
687 let raw_magnitude_str: Result<String, FormatSpecError> = match &self.format_type {
688 Some(FormatType::FixedPoint(case)) => Ok(float::format_fixed(
689 precision,
690 magnitude,
691 *case,
692 self.alternate_form,
693 )),
694 Some(FormatType::Decimal)
695 | Some(FormatType::Binary)
696 | Some(FormatType::Octal)
697 | Some(FormatType::Hex(_))
698 | Some(FormatType::String)
699 | Some(FormatType::Character)
700 | Some(FormatType::Number(Case::Upper))
701 | Some(FormatType::Unknown(_)) => {
702 let ch = char::from(self.format_type.as_ref().unwrap());
703 Err(FormatSpecError::UnknownFormatCode(ch, "float"))
704 }
705 Some(FormatType::GeneralFormat(case)) | Some(FormatType::Number(case)) => {
706 let precision = if precision == 0 { 1 } else { precision };
707 Ok(float::format_general(
708 precision,
709 magnitude,
710 *case,
711 self.alternate_form,
712 false,
713 ))
714 }
715 Some(FormatType::Exponent(case)) => Ok(float::format_exponent(
716 precision,
717 magnitude,
718 *case,
719 self.alternate_form,
720 )),
721 Some(FormatType::Percentage) => match magnitude {
722 magnitude if magnitude.is_nan() => Ok("nan%".to_owned()),
723 magnitude if magnitude.is_infinite() => Ok("inf%".to_owned()),
724 _ => {
725 let result = format!("{:.*}", precision, magnitude * 100.0);
726 let point = float::decimal_point_or_empty(precision, self.alternate_form);
727 Ok(format!("{result}{point}%"))
728 }
729 },
730 None => match magnitude {
731 magnitude if magnitude.is_nan() => Ok("nan".to_owned()),
732 magnitude if magnitude.is_infinite() => Ok("inf".to_owned()),
733 _ => match self.precision {
734 Some(precision) => Ok(float::format_general(
735 precision,
736 magnitude,
737 Case::Lower,
738 self.alternate_form,
739 true,
740 )),

Callers 6

format_float_localeMethod · 0.45
format_boolMethod · 0.45
format_intMethod · 0.45
spec_format_bytesFunction · 0.45
spec_format_stringFunction · 0.45
__format__Method · 0.45

Calls 15

format_fixedFunction · 0.85
format_generalFunction · 0.85
format_exponentFunction · 0.85
decimal_point_or_emptyFunction · 0.85
newFunction · 0.85
validate_formatMethod · 0.80
absMethod · 0.80
format_sign_and_alignMethod · 0.80
ErrClass · 0.50
to_stringFunction · 0.50
unwrapMethod · 0.45

Tested by

no test coverage detected