Adding Decimal to an Integer - powershell

I need to add decimal to an integer.
Eg:
Amount = 12345
The output should be
Amount = 123.45
Could someone help me how to achieve this using power shell

Always use a comma if you're looking to format a long string, adding a decimal point implies the number has a decimal component.
(12345).ToString("N0")
12,345
the N0 is a default formatting string which here gives the comma separated string.
if you're looking to fix badly stored decimal numbers or something where your question is actually what you're looking for, dividing by 100 will work for your needs.
12345 / 100
123.45
if you need a more code based solution which handles trailing zeroes or something you could use this:
$num = 12345
$numstr = "$num"
$splitat = $numstr.Length - 2
$before = $numstr.Substring(0,$SplitAt)
$after = $numstr.Substring($SplitAt)
"$($before).$($after)"
or this
"12345" -replace '(\d*)(\d{2})','$1.$2'

Related

What is the fastest/easiest way to increase a number in a string variable in Powershell?

I have the following Powershell variable
$var = "AB-0045"
I would like to increase the number in the string to become "AB-0046".
I can do:
$newNumber = [int]$var.Substring($var.length -4,4) + 1
Which will give me the desired number 46, but then I have to append that 46 as a string to a new string "AB-00".
Is there a better way to do that?
Now that you have the integer, you'll have to convert back to string formatted in the way you'd like and concatenate.
I'd recommend adding to "AB-" rather than "AB-00" in case your number goes over 100.
To pad leading zeros, you can use the -f operator.
e.g. "{0:d4}" -f 45
You'll still need to get the integer first (45 in the example) from your original string.
I tested with regex class Replace() method and string class Split() method with string formatter. Split() seems faster provided your string is always in the same format. The Replace() method does not care what happens before the last 4 numbers:
# Replace Method
[regex]::Replace($var,'\d{4}$',{([int]$args[0].Value+1).ToString('0000')})
# Split method
$a,[int]$b = $var.split('-'); "{0}-{1:0000}" -f $a,++$b

Trying to convert the number numeric value in this string to a percent. Is there any easy way to do this in powershell?

Trying to convert the number numeric value in this string to a percent. Is there any easy way to do this in powershell?
"Percentage of records ","0.02"
So, the output would look like :
Percentage of records , 2%
Thanks in advance for any suggestions you can provide.
Yes, you can convert the string to a float data type (single, double, decimal), and then convert it back using a format string, like so:
"Percentage of records ", ([double]'0.02').ToString('P0')
And if you want it to output in a single line, you could use:
"Percentage of records: $(([double]'0.02').ToString('P0'))"
Explanation:
Convert your string to a float datatype: [double]'0.02'
Convert that float back into a string: .ToString()
But we want to format it as a percentage, so we supply P0 as a parameter.
i. P - means to format the value as a percentage, this performs the N * 100 operation for you and then adds on the percent sign
ii. 0 - controls the number of decimal places to show. In your case, you want to show zero decimal places.
Note: The percentage format string will round your value to the nearest decimal that you specify.
Example:
0.021.ToString('P0')
# returns 2%
0.025.ToString('P0')
# returns 3%
As #mklement0 pointed out in the comments. I hadn't considered that your sample may be a single string, like:
'"Percentage of records ","0.02"'
I assumed it was two strings, which you separated with a comma.
In the event it is a single string, then you need to extract the number to use it. Once you have isolated the number, then you can use my advice above:
$yourString = '"Percentage of records ","0.02"'
# probably the more "proper" way
$pctValue = ($yourString -split ',' -replace '"')[1]
# or
# a hacky way I just thought of that happens to work in this scenario
$pctValue = (iex $yourString)[1]
Explanation of first example:
-split ',' - Take the string, and break it out into multiple strings, separating them by comma
-replace '"','' - Replace all instances of " with blank. The second parameter is optional since you are removing. Could be written as -replace '"'
(...)[1] - This is saying to take the SECOND string that it returned (starts at zero). In this case it would be your 0.02 value.
Explanation of second example (this is a bit of a hack, but thought it would be fun to include anyway):
iex - alias for Invoke-Expression - it's telling powershell to run whatever is inside of the string verbatim. So it's the equivalent of typing "Percentage of records ","0.02" into powershell and hitting enter. Which in PowerShell terms, that is the equivalent of passing it a list of strings.
Use -f (format operator) in powerhsell for build your string :
"Percentage of records, {0:0%} " -f 0.02
or in percentage :
"Percentage of records, {0:P0} " -f 0.02

How to format a number into NN.nn style

I am handling a stream of numbers from sensors and want to format them to a 'standard' layout centered on the decimal point, as per the following: 1.00 = 01.00 | 12.9 = 12.90 | 2 = 02.00 | 49.09 = 49.09 etc.
I have tried zfill and round - including combinations but the decimal point moves in everything I have tried so far. The purpose is to fill pre-defined fields for later analysis.
UPDATE
Probably not the most elegant solution but I came up with this, which works a far as I have been able to test so far:
For padding to the left of decimal point:
def zfl(d, chrs, pad):
# Pads the provided string with leading 'pad's to suit the specified
# 'chrs' length.
# When called, parameters are : d = string, chrs = required length of
# string and pad = fill characters
# The formatted string of correct length and added pad characters is
# returned as string
frmtd_str = str(d)
while len(frmtd_str) != chrs:
# less then required characters
frmtd_str = pad + frmtd_str
return(frmtd_str)`
Function for padding to the right of decimal point:
def zfr(d, chrs, pad):
# Pads the provided string with trailing 'pad's to suit the specified
# 'chrs' length
# When called, parameters are : d = string, chrs = required length of
# string and pad = fill characters
# The formatted string of correct length and added pad characters is
# returned as string
frmtd_str = str(d)
while len(frmtd_str) != chrs:
# less then required characters
frmtd_str = frmtd_str + pad
return(frmtd_str)
Example to call the above funtions:
The original data is split into two parts using the decimal as the seperator:
dat_splt = str(Dat[0]).split(".",2)
Then the padding carried out and reconstructed for use:
exampledat = "{}.{}".format(zfl(dat_splt[0],3,'0'), zfr(dat_splt[1],3,'0'))
Notes:
To pad out either side requires the parameters for string, character required and the 'pad' character.
The characters required can be anything (only tested with 1 to 10)
The final returned string can be asymmetrical i.e. nnnnn.nn or n.nnn
The number of characters in each part of the original data is accommodated.
Quite happy with the results from this and it is reusable as common functions. I am sure there are more 'economical/efficient' methods but I haven't found those yet and at least this works, giving nice orderly and stable text string result lists (which is what I was aiming for at this point).
Hope I got the layout correct.. :-)
'{:0>5.2f}'.format(n)
'{:0>5.2f}'.format(1)
'01.00'
'{:0>5.2f}'.format(12.9)
'12.90'
'{:0>5.2f}'.format(49.09)
'49.09'
https://queirozf.com/entries/python-number-formatting-examples#left-padding-with-zeros

Convert number to currency

We need to convert a plain number to a currency value. However, nothing we find seems to work.
We tried the basic code below, but that returns a value of $123,456.00 when it should be $1,234.56.
$rawNumber = 123456
$newNumber = 0
$newNumber = "{0:c}" -f $rawNumber
We tried different iterations of "{0:c}" (c2, c1,etc), but it always returns a number, but just adding zeroes on to the end.
We tried converting the number to a string and inserting the decimal, commas and dollar sign, but we're dealing with numbers that can be as short as two or as long as ten, so it becomes something of a beast to try and plan for every possible combination.
Are we missing something obvious to easily convert numbers to a currency value?
Thank you for any help you can provide.
If you have a subdivision of the primary unit of a currency, you need to divide the input value to get the number of primary units, in this case:
$dollars = $rawNumber / 100
$formattedString = '{0:C}' -f $dollars
Beware that the resulting formatted string will depend on the current locale. You can pass a [cultureinfo] object to the ToString() method of the target object instead if you want a specific locale enforced. Here shown with en-US, de-DE and da-DK:
PS C:\> 'en-US','de-DE','da-DK' |ForEach-Object { $dollars.ToString('C',[cultureinfo]$_) }
$1,234.56
1.234,56 €
1.234,56 kr.
You can format the input using {0:C2} the 2 in C2 is the amount of decimal places.
Example:
$rawNumber = 123456
$newNumber = 0
$newNumber = "{0:C2}" -f $rawNumber

Extrating the digits before the decimal point with Powershell

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
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' [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)