Looking at your examples, it seems you want to:
- Show at most 2 decimal places for numbers >= 0.01
- Show all necessary decimal places for smaller numbers
- Remove trailing zeros
Here's a Rust function that implements this formatting:
fn format_f64(value: f64) -> String {
if value.abs() >= 0.01 {
// For numbers >= 0.01, use at most 2 decimal places
let formatted = format!("{:.2}", value);
// Remove trailing zeros and unnecessary decimal point
let trimmed = formatted.trim_end_matches('0').trim_end_matches('.');
trimmed.to_string()
} else if value == 0.0 {
"0".to_string()
} else {
// For smaller numbers, use enough precision to show the value
// Start with a reasonable precision and increase if needed
for precision in 1..=15 {
let formatted = format!("{:.prec$}", value, prec = precision);
let parsed: f64 = formatted.parse().unwrap();
// Check if we've captured the value accurately
if (parsed - value).abs() / value.abs() < 1e-10 {
return formatted.trim_end_matches('0').to_string();
}
}
// Fallback to scientific notation or full precision
format!("{}", value)
}
}
fn main() {
println!("{} => {}", 0.1, format_f64(0.1));
println!("{} => {}", 0.01, format_f64(0.01));
println!("{} => {}", 0.99999, format_f64(0.99999));
println!("{} => {}", 0.000001, format_f64(0.000001));
// Additional test cases
println!("{} => {}", 0.5, format_f64(0.5));
println!("{} => {}", 1.0, format_f64(1.0));
println!("{} => {}", 0.123, format_f64(0.123));
println!("{} => {}", 0.0000123, format_f64(0.0000123));
}
Alternatively, here's a simpler approach using the format! macro with conditional logic:
fn format_f64_simple(value: f64) -> String {
if value == 0.0 {
return "0".to_string();
}
if value.abs() >= 0.01 {
// Format with 2 decimal places and remove trailing zeros
format!("{:.2}", value)
.trim_end_matches('0')
.trim_end_matches('.')
.to_string()
} else {
// For small numbers, use general formatting which handles them well
format!("{}", value)
}
}
If you need more control or have specific edge cases, you might want to use a more sophisticated approach with a decimal library like rust_decimal or implement custom logic based on the number of significant figures.