1

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?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Will this work for you?

[math]::Floor(22/8)

Result: 2

2 Comments

To strip decimal places after the decimal point, use truncate instead of floor. This will produce the correct result, even for negative numbers.
@jonZ Good call I wasn't aware of truncate method. I think it will better satisfy all cases for AXN's need to "strip all the decimal places after the decimal point".
1

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.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.