Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the scale of a given decimal

How can I count the scale of a given decimal in Powershell?

$a = 0.0001
$b = 0.000001

Casting $a to a string and returning $a.Length gives a result of 6...I need 4.

I thought there'd be a decimal or math function but I haven't found it and messing with a string seems inelegant.

like image 301
felixmc Avatar asked Jan 19 '26 02:01

felixmc


1 Answers

There's probably a better mathematic way but I'd find the decimal places like this:

$a = 0.0001
$decimalPlaces = ("$a" -split '\.')[-1].TrimEnd('0').Length

Basically, split the string on the . character and get the length of the last string in the array. Wrapping $a in double-quotes implicitly calls .ToString() with an invariant culture (you could expand this as $a.ToString([CultureInfo]::InvariantCulture)), making this method to determine the number of decimal places culture-invariant.

.TrimEnd('0') is used in case $a were sourced from a string, not a proper number type, it's possible that trailing zeroes could be included that should not count as decimal places. However, if you want the scale and not just the used decimal places, leave .TrimEnd('0') off like so:

$decimalPlaces = ("$a" -split '\.')[-1].Length
like image 175
Bender the Greatest Avatar answered Jan 20 '26 16:01

Bender the Greatest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!