Why isn't my string converting to float in PowerShell?

July 15, 2025 5 answers
Asked by 7th clue hidden
I'm working on a function in my PowerShell script that checks if two price points are within an acceptable range. The issue I'm having is with casting string parameters to float. Specifically, I have two parameters, `$p1` and `$p2`, both declared as strings. When I try to cast them to float, I notice that instead of getting the expected `System.Single` type, it retains `System.String`. I tested casting a string in the console directly, and it worked fine, so I'm wondering if there's something about the function structure that's causing this. Any ideas?

Answers

6 thermos refills
It looks like youโ€™re trying to cast the strings to float after they've already been defined as strings in the parameters. Once they're declared, PowerShell can get a bit tricky with types. A suggestion would be to try something like this: `$p1 = [float]$p1` after you clean up the dollar sign.

paddle-wheel mechanics: Thanks for the tip! I didnโ€™t realize that would cause issues.

Reply to this answer
somewhat plausible
I think your problem might stem from the way you're checking for the dollar sign. Try using a switch to remove it, like `$p1 = $p1 -replace '$'` before casting to float. That could make the casting clearer for PowerShell.
Reply to this answer
4wk_seedling
You might be hitting a type conversion wall here. Instead of trying to change the original parameter types directly, it might be better to create new variables. For instance, using `$q1 = [float]$p1` would be a cleaner way to handle it without running into type issues.

ink drying time+: That makes total sense! Iโ€™ll give that a try.

Reply to this answer
MATH.oddity
One thing I noticed is that you're using double quotes for your if checks, which can introduce issues with variable evaluation. Try switching to single quotes for matching literals or use backticks to escape the dollar sign. That could help fix your type casting issue as well.

7th clue hidden: Got it, I'll modify that!

Reply to this answer
stress2weak
Have you considered using the `Parse()` method from the system? That might help with any tricky string format issues you have. You can do something like `$p1 = [system.double]::Parse($p1)` to ensure it converts correctly.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions