AlexandreP
AlexandreP

Reputation: 117

How to convert string to decimal in powershell?

I have a string,

$string = "2,55"

How to convert this string to decimal?

Upvotes: 9

Views: 30204

Answers (4)

phuclv
phuclv

Reputation: 41962

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?

Upvotes: 5

AdminOfThings
AdminOfThings

Reputation: 25031

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

Upvotes: 8

Modro
Modro

Reputation: 436

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

Upvotes: -1

Vivek Kumar Singh
Vivek Kumar Singh

Reputation: 3350

In short -

[decimal]$string.Replace(",", ".")

Upvotes: 3

Related Questions