Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format an f32 with a specific precision and prepended zeros?

What format string should I use in the println! macro in order to print 0.0 as 00000.000?

println!("={:05.3}", 0.0);

Output: =0.000

Expected: =00000.000

like image 639
chabapok Avatar asked Apr 11 '18 15:04

chabapok


People also ask

What is f32 in Rust?

pub fn powi(self, n: i32) -> f32Raises a number to an integer power. Using this function is generally faster than using powf .

How do you round in Rust?

pub fn round(self) -> f64 Returns the nearest integer to self . Round half-way cases away from 0.0 .

What does format do in Rust?

Creates a String using interpolation of runtime expressions.


1 Answers

The first number (after the zero) is the total number of characters.

So you do display your number with 5 characters. If you want to have 5 numbers before the dot, you must type:

println!("{:09.3}", 123.45);

Output: 00123.450

Because 9 minus 3 minus the dot = 5 digits.

like image 171
Boiethios Avatar answered Sep 17 '22 18:09

Boiethios