I have a string,
$string = "2,55"
How to convert this string to decimal?
I have a string,
$string = "2,55"
How to convert this string to decimal?
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 other answers actually work (although it may appear to work). For more details read How can I convert a string such as 5.7303333333e+02 to decimal in PowerShell?
To force a conversion to a specific datatype, prefix the value or variable with the type in square brackets, this is known as a Cast Operator and forces the chosen datatype:
$string = "100.5"
$decimal = [decimal]$string
$string + 0.5
# Outputs 100.10.5
$decimal + 0.5
# Outputs 101,0
More information can be found here
.. 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.