Reputation: 13
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
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
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
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