7

I have a string,

$string = "2,55"

How to convert this string to decimal?

phuclv
  • 37,963
  • 15
  • 156
  • 475
AlexandreP
  • 87
  • 1
  • 1
  • 6
  • Please refere [How to ask](https://stackoverflow.com/help/how-to-ask)..Have you tried any code or do you have any research content to show for this issue ? – Nirav Mistry Aug 08 '19 at 09:56
  • 3
    Possible duplicate of [How can I convert a string such as 5.7303333333e+02 to a decimal type in PowerShell?](https://stackoverflow.com/questions/16966938/how-can-i-convert-a-string-such-as-5-7303333333e02-to-a-decimal-type-in-powersh) – Oliver Nybo Aug 08 '19 at 09:57

4 Answers4

6

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
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27
4

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?

phuclv
  • 37,963
  • 15
  • 156
  • 475
3

In short -

[decimal]$string.Replace(",", ".")
Vivek Kumar Singh
  • 3,223
  • 1
  • 14
  • 27
-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

Modro
  • 416
  • 2
  • 14
  • 1
    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 Aug 08 '19 at 13:35
  • 1
    @mklement0, thanks for the feedback. I missed this detail. – Modro Aug 08 '19 at 13:43