brechtvhb
brechtvhb

Reputation: 1048

Rounding and padding a decimal

Hello I have a decimal which I want to round and want to pad.

Is it possible to do this in one command

Rounding can be done as follows

 $"{myDecimal:F0}"

padding can be done as follows

$"{myDecimal:D6}"

is it possible to do both at once?

Here are some examples:

30 => 000030
30.02 => 000030
30.6 => 000031
30000 => 030000

Upvotes: 1

Views: 397

Answers (2)

Corak
Corak

Reputation: 2788

You are not restricted to the standard format specifiers. You can use custom format specifiers to create, well, custom formats. With the added bonus, that rounding (AFAIK "away from zero" by default) is already included.

So F0 means: no decimal places (i.e. round to full integer) and D6 (for integers, not for decimals; thanks juharr) means: fill up to six digits.

Which is what this custom format does "combined":

$"{myDecimal:000000}"

Upvotes: 3

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30205

Would that work for you?

$"{Math.Round(myDecimal):D6}"

Upvotes: 0

Related Questions