2

I am using Powershell and need to extract the digits before the decimal point so that I can evaluate the number extracted

So with $Interest_Rate = 15.5

I have tried the following code .. but they do not work:

$Interest_RatePart1 = "{0:N0}" -f $Interest_Rate

It rounds the value to 16

$Interest_RatePart1 = ($Interest_Rate -split '.')[0].trim()

It returns a blank. I just want to return 15

hdsouza
  • 354
  • 4
  • 17

2 Answers2

5

Formatting the number will cause rounding away from zero

Use Math.Truncate() - which always rounds towards zero - instead:

$Interest_RatePart1 = [Math]::Truncate($Interest_Rate)

FWIW, the reason your last attempt returns nothing, is because -split defaults to regular expressions, and . means any character in regex.

Either escape the . with \:

$Interest_RatePart1 = ($Interest_Rate -split '\.')[0].Trim()

or specify that it shouldn't use regex:

$Interest_RatePart1 = ($Interest_Rate -split '.', 2, 'SimpleMatch')[0].Trim()

or use the String.Split() method instead:

$Interest_RatePart1 = "$Interest_Rate".Split('.')[0].Trim()
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
2

Mathias' [Math]::Truncate is correct - some other options for you though, pay attention to Floor as it is Slightly Different to Truncate when working with negative numbers.

  • Cast to int (can round up)

    [int]$Interest_Rate
    
  • Use [Math]::Floor (will always round down, similar to truncate for non-negative numbers)

    [Math]::Floor($Interest_Rate)
    
  • Use [Math]::Round with 0 decimal places. (can round up)

    [Math]::Round($Interest_Rate, 0)
    
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
colsw
  • 3,216
  • 1
  • 14
  • 28
  • 3
    `Math.Truncate()` _always_ rounds toward zero (basically truncating the _absolute value_ of the input argument), it's similar to your last example rather than `Math.Floor()` – Mathias R. Jessen Jan 27 '18 at 16:31
  • 2
    Truncate: `[math]::Truncate(1.5) == 1`, `[math]::Truncate(2.5) == 2`, `[math]::Truncate(-1.5) == -1`, `[math]::Truncate(-2.5) == -2` – Ansgar Wiechers Jan 27 '18 at 18:15
  • 2
    Floor: `[math]::Floor(1.5) == 1`, `[math]::Floor(2.5) == 2`, `[math]::Floor(-1.5) == -2`, `[math]::Floor(-2.5) == -3` – Ansgar Wiechers Jan 27 '18 at 18:15
  • 2
    Round: `[math]::Round(1.5, 0) == 2`,`[math]::Round(2.5, 0) == 2`, `[math]::Round(-1.5, 0) == -2`, `[math]::Round(-2.5, 0) == -2` – Ansgar Wiechers Jan 27 '18 at 18:15
  • 1
    @AnsgarWiechers nice. You could also implement `Truncate()` using `Floor()` and `Abs()`: `$v = 1.5; [Math]::Floor([Math]::Abs($v)) * (1,-1)[$v -lt 0]` – Mathias R. Jessen Jan 28 '18 at 00:50