Hi

How do I print a decimal number to three decimal places if the decimal number has more than three decimal places.

Thanks

Spencer

Hi

How do I print a decimal number to three decimal places if the decimal number has more than three decimal places.

Thanks

Spencer

Use the formatting specifier `{:.3}`

to print with a precision of 3 decimal places:

```
let x = 1.23456;
println!("{:.3}", x); // prints "1.234"
```

See the fmt docs for more info.

2 Likes

It will print 1.235 though.

Because the 4th decimal is a 5.

3 Likes

```
let x = 1.23456;
println!("{:.5}", x.to_string()); // prints "1.234"
```

For strings, this specifies the total width rather than the number of decimal places. Only floating-point types can be formatted with specific decimal-place precision.

Without knowing that yeah. Use a decimal type if rounding is a problem.

@sdf1444 You have asked a lot of basic, generic questions in a quick succession. Please make some learning and research effort yourself. Read the Rust Book or learn for other tutorials nad examples online. Members of this forum can't be expected to spoon-feed you with all of the basics of Rust and programming in general.

1 Like