How to convert string to decimal in powershell?
Solution 1
In short -
[decimal]$string.Replace(",", ".")
Solution 2
Another way of converting this (not necessarily better) is using the ToDecimal
method with a specific culture. Here I'm using the standard french culture.
[System.Convert]::ToDecimal("2,55",[cultureinfo]::GetCultureInfo('fr-FR'))
2.55
Solution 3
You should convert using the current locale. Replacing ,
with .
isn't reliable and is slightly slower (because another string must be created). Both Parse and TryParse have a culture parameter that you can use
PS D:\> $string = "2,55"
PS D:\> $culture = Get-Culture
PS D:\> [decimal]::Parse($string, $culture)
2.55
PS D:\> [decimal]$dec = 0
PS D:\> [decimal]::TryParse($string, [Globalization.NumberStyles]::Float, $culture, [ref]$dec)
True
PS D:\> $dec
2.55
If you know the locale of the input then parse directly in that locale by using GetCultureInfo
$culture = [cultureinfo]::GetCultureInfo('fr-FR')
Note that if the string contains the exponent like "2,55e2" then none of the current answers actually work (although it may appears to work). For more details read How can I convert a string such as 5.7303333333e+02 to decimal in PowerShell?
AlexandreP
Updated on June 27, 2022Comments
-
AlexandreP almost 2 years
I have a string,
$string = "2,55"
How to convert this string to decimal?
-
mklement0 over 4 yearsThat's helpful in general, but note that PowerShell's casts always apply the invariant culture, where the decimal mark is
.
. Therefore, the OP's input string wouldn't yield the desired result:[decimal] "2,55"
->255
; that is, the,
was interpreted as a thousands-grouping symbol and effectively ignored. -
Modro over 4 years@mklement0, thanks for the feedback. I missed this detail.