IT Questions and Answers :)

Monday, November 30, 2020

In PowerShell, which of the following expressions round a floating point number contained in the variable $Num to 2 decimal places?

In PowerShell, which of the following expressions round a floating point number contained in the variable $Num to 2 decimal places?

  • Get-RoundNumber -Number $Num -Precision 2
  • $Num -round 2
  • $Num.Round(2)
  • [Math]::Round($Num, 2) 
 
In PowerShell, which of the following expressions round a floating point number contained in the variable $Num to 2 decimal places?

EXPLANATION

As of PowerShell version 5, there is no native PowerShell cmdlet to round numbers; additionally, floating point types do not contain a method to accomplish this.  The best way to round a number to a certain precision is to utilize the .NET framework's System.Math class, which contains the static method Round().

Technically, Math.Round() only accepts numbers of the type double or decimal, but passing it a float (also known as a single) will automatically convert that number to a double for this purpose.

The above example and solution uses the following definition of Round():

static double Round(double value, int digits)

Additional documentation on the System.Math.Round() method:https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx
 
 
Share:

0 comments:

Post a Comment

Popular Posts