AXN
AXN

Reputation: 13

Powershell - number format shows incorrect result

in powershell v2, I need to divide 22 by 8 and then strip all the decimal places after the decimal point (which is on my system a comma). No rounding.

As you see. 22/8 equals 2,75

PS C:\Documents and Settings\Administrator> $(22/8)
2,75

Expected result is 2.

Strangely, I get different results when using different ways to calculate the same.

PS C:\Documents and Settings\Administrator> "{0:N0}" -f $(22/8)
3

PS C:\Documents and Settings\Administrator> "{0:N0}" -f 2.75
3

PS C:\Documents and Settings\Administrator> "{0:N0}" -f 2,75
2

Some other examples...

PS C:\Documents and Settings\Administrator> "{0:N0}" -f 2.15
2

PS C:\Documents and Settings\Administrator> "{0:N0}" -f 2,15
2

What is the cause?

Upvotes: 1

Views: 1239

Answers (4)

Shay Levy
Shay Levy

Reputation: 126762

Math methods are much more prefer ed but you can also resort to string manipulation:

PS> (22/8).ToString().Split('.')[0]
2

Upvotes: 0

jon Z
jon Z

Reputation: 16626

To strip all the decimal places after the decimal point, you should use the truncate method of the math class.

[Math]::Truncate(22/8) # result: 2
[Math]::Truncate(-22/8) # result: -2

This will give the desired result, both for positive and negative numbers.

Upvotes: 3

Andy Arismendi
Andy Arismendi

Reputation: 52609

Will this work for you?

[math]::Floor(22/8)

Result: 2

Upvotes: 1

John Fisher
John Fisher

Reputation: 22719

The comma (at least on US English systems) is used by Powershell as a separator. If that is the case on your machine, the "2,75" is read as a "2" and a "75". The format string only cares about the "2", so it ignores the "75" which it views as the second argument.

The 2.15 rounds down, and the 2.75 rounds up.

So, why do you expect "2.75" to round down to "2"? If that is what you really want, then try the Math.Floor() method.

Upvotes: 1

Related Questions