# Format a number with two decimals

• ### Question

• I see there's a method for the Double type called .ToDecimal()

I was wondering how that can be used. I am trying to output a number with lots of decimals to a number with only two decimals so that it will be easier to read

Tuesday, August 23, 2016 8:23 AM

### Answers

• OK:

[convert]::ToDecimal(3.22)

PS D:\scripts> \$x=3.4567
PS D:\scripts> [convert]::ToDecimal(\$x)
3.4567

Works perfectly.

\_(ツ)_/

• Proposed as answer by Wednesday, August 24, 2016 4:53 AM
• Marked as answer by Tuesday, September 6, 2016 3:23 AM
Tuesday, August 23, 2016 11:50 AM

### All replies

• You can use the -f operator in PowerShell to format numbers:

Formatting Numbers

Tuesday, August 23, 2016 8:40 AM
• Hello

\$a = 256

"{0:D4}" -f \$a

D - The value is displayed using the number of digits in the precision specifier

For More

https://technet.microsoft.com/en-us/library/ee692795.aspx

Regards, Regin Ravi

• Proposed as answer by Wednesday, August 24, 2016 4:52 AM
• Unproposed as answer by Wednesday, August 24, 2016 4:53 AM
Tuesday, August 23, 2016 8:43 AM
• PS > 123.45678
123.45678
PS > (123.45678).ToString('N2')
123.46

\_(ツ)_/

Tuesday, August 23, 2016 10:23 AM
• You can also use

`[math]::round(\$yourNumber,2)`

to get is as a rounded double if you want to use it for further calculations. -f and ToString return string objects.

Futhermore, you can use

`\$yourNumber.ToString(0.0000)`

if you want other amounts of decimal places than 2.

Best wishes

Christoph

Tuesday, August 23, 2016 10:36 AM
• But can't I just use the ToDecimal() in a way? Why else does it exist?

Freddy

Tuesday, August 23, 2016 11:15 AM
• OK:

[convert]::ToDecimal(3.22)

PS D:\scripts> \$x=3.4567
PS D:\scripts> [convert]::ToDecimal(\$x)
3.4567

Works perfectly.

\_(ツ)_/

• Proposed as answer by Wednesday, August 24, 2016 4:53 AM
• Marked as answer by Tuesday, September 6, 2016 3:23 AM
Tuesday, August 23, 2016 11:50 AM
• Numbers (school math)

PS > [decimal]::MaxValue
79228162514264337593543950335
PS > [decimal]::MinValue
-79228162514264337593543950335
PS > [float]::MaxValue
3.402823E+38
PS > [float]::MinValue
-3.402823E+38
PS > [double]::MaxValue
1.79769313486232E+308
PS > [double]::MinValue
-1.79769313486232E+308
PS >
PS > [int]::MaxValue
2147483647
PS > [int]::MinValue
-2147483648
PS >

Rounding:

[math]::round(\$yourNumber,2)

Formatting:

(1.2345).ToString('N2')

\_(ツ)_/

Tuesday, August 23, 2016 11:56 AM