How to format a number into NN.nn style - micropython

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

Related

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

Adding Decimal to an Integer

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'

Converting a hex to string in Swift formatted to keep the same number of digits

I'm trying to create a string from hex values in an array, but whenever a hex in the array starts with a zero it disappears in the resulting string as well.
I use String(value:radix:uppercase) to create the string.
An example:
Here's an array: [0x13245678, 0x12345678, 0x12345678, 0x12345678].
Which gives me the string: 12345678123456781234567812345678 (32 characters)
But the following array: [0x02345678, 0x12345678, 0x02345678, 0x12345678] (notice that I replaced two 1's with zeroes).
Gives me the string: 234567812345678234567812345678 (30 characters)
I'm not sure why it removes the zeroes. I know the value is correct; how can I format it to keep the zero if it was there?
The number 0x01234567 is really just 0x1234567. Leading zeros in number literals don't mean anything (unless you are using the leading 0 for octal number literals).
Instead of using String(value:radix:uppercase), use String(format:).
let num = 0x1234567
let str = String(format: "%08X", num)
Explanation of the format:
The 0 means to pad the left end of the string with zeros as needed.
The 8 means you want the result to be 8 characters long
The X means you want the number converted to uppercase hex. Use x if you want lowercase hex.

Function to split string in matlab and return second number

I have a string and I need two characters to be returned.
I tried with strsplit but the delimiter must be a string and I don't have any delimiters in my string. Instead, I always want to get the second number in my string. The number is always 2 digits.
Example: 001a02.jpg I use the fileparts function to delete the extension of the image (jpg), so I get this string: 001a02
The expected return value is 02
Another example: 001A43a . Return values: 43
Another one: 002A12. Return values: 12
All the filenames are in a matrix 1002x1. Maybe I can use textscan but in the second example, it gives "43a" as a result.
(Just so this question doesn't remain unanswered, here's a possible approach: )
One way to go about this uses splitting with regular expressions (MATLAB's strsplit which you mentioned):
str = '001a02.jpg';
C = strsplit(str,'[a-zA-Z.]','DelimiterType','RegularExpression');
Results in:
C =
'001' '02' ''
In older versions of MATLAB, before strsplit was introduced, similar functionality was achieved using regexp(...,'split').
If you want to learn more about regular expressions (abbreviated as "regex" or "regexp"), there are many online resources (JGI..)
In your case, if you only need to take the 5th and 6th characters from the string you could use:
D = str(5:6);
... and if you want to convert those into numbers you could use:
E = str2double(str(5:6));
If your number is always at a certain position in the string, you can simply index this position.
In the examples you gave, the number is always the 5th and 6th characters in the string.
filename = '002A12';
num = str2num(filename(5:6));
Otherwise, if the formating is more complex, you may want to use a regular expression. There is a similar question matlab - extracting numbers from (odd) string. Modifying the code found there you can do the following
all_num = regexp(filename, '\d+', 'match'); %Find all numbers in the filename
num = str2num(all_num{2}) %Convert second number from str

how to change display in gtk.spinbutton

I have a gtk.spinbutton and I want to set the digits according to the locale
format.
like say I have a locale installed hungarian so my decimal separator is
'.'(dot) and thousand separator is ','(comma) eg: my spinbutton value is
1131191 so after the user focus out of the gtk.spinbutton my value should
convert to 11,311.91 . the conversion is made by me but I am not able to set
it to gtk.spinbutton either using set_text / set_value method.
Any help is appreciated !
Thanks
Formatting a SpinButton can be done by handling the output signal.
locale.setlocale(locale.LC_ALL, '')
def output(spin):
digits = int(spin.props.digits)
value = spin.props.value
text = locale.format('%.*f', (digits, value), True)
spin.props.text = text
return True
spin.connect('output', output)
If you also want to let users enter values in the localised format (e.g. let the user type "1,000" instead of "1000"), handle the input signal.
def input(spin, new_value):
text = spin.props.text
try:
value = locale.atof(text)
except ValueError:
return -1
p = ctypes.c_double.from_address(hash(new_value))
p.value = value
return True
spin.connect('input', input)
(This code is longer than it should be because PyGTK does not properly wrap input, hence the ctypes hack. It's just parsing the text and then assigning the numeric value to a pointer location.)
Credits: The ctypes hack and digits formatting are inspired by Tim Evans's post in the PyGTK mailing list.