9

I have a string,

$string = "2,55"

How to convert this string to decimal?

2

4 Answers 4

8

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
Sign up to request clarification or add additional context in comments.

Comments

5

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?

Comments

3

In short -

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

2 Comments

love the conciseness !
@jyao consise != correct. Try running that on .NET Core on a comma locale and it'll fail immediately
-1

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

2 Comments

That'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.
@mklement0, thanks for the feedback. I missed this detail.

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.