Skip to content

How to Remove everything after the decimal place from a number in PowerShell

In PowerShell, you can remove everything after the decimal place from a number stored as a string or a floating-point number using various methods. Lets imagine we have the number “82.91373001”, and we wish to remove the numbers after the decimal place to give us 82.

Below are a few approaches to achieve this:

Using String Manipulation

If your variable is a string, you can use string manipulation to remove everything after the decimal place.

# Example string variable
$numberString = "82.91373001"

# Split the string at the decimal point and take the first part
$integerPart = $numberString.Split('.')[0]

# Output the result
$integerPart

Using Type Conversion (Casting)

If your variable is a number, you can cast it to an integer to remove the decimal part.

# Example floating-point number variable
$number = 82.91373001

# Cast the number to an integer
$integerPart = [int]$number

# Output the result
$integerPart

Using Math Functions

Alternatively, you can use mathematical functions to achieve the same result.

Using [Math]::Truncate()

# Example floating-point number variable
$number = 82.91373001

# Use the Math.Truncate method to remove the decimal part
$integerPart = [Math]::Truncate($number)

# Output the result
$integerPart

Using [Math]::Floor()

Another way to achieve this, which will also handle negative numbers correctly (truncating towards zero), is using [Math]::Floor():

# Example floating-point number variable
$number = 82.91373001

# Use the Math.Floor method to remove the decimal part
$integerPart = [Math]::Floor($number)

# Output the result
$integerPart

Summary

  • String Manipulation: Suitable when the number is in string format.
  • Type Conversion: Direct and efficient for numerical variables.
  • Math Functions: Useful for more advanced scenarios or when you want to ensure proper handling of floating-point numbers.

Here is a combined example that demonstrates all three methods:

# String manipulation
$numberString = "82.91373001"
$integerPartString = $numberString.Split('.')[0]

# Type conversion
$number = 82.91373001
$integerPartConversion = [int]$number

# Math function (Truncate)
$integerPartTruncate = [Math]::Truncate($number)

# Output results
"String Manipulation: $integerPartString"
"Type Conversion: $integerPartConversion"
"Math Truncate: $integerPartTruncate"

Choose the method that best fits your needs based on the format of your input data and the context in which you are working.

Published inPowerShell
© 2024 ScriptWizards.net - Powered by Coffee & Magic