how to change display in gtk.spinbutton - gtk

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.

Related

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

Formatting Localized Strings with Multiple Values

I've created a localized string that takes the form similar to
"text_key" = "Collected %d out of %d";
and am using the following formatter:
let numberOfItems = 2
let totalNumberOfItems = 10
let format = NSLocalizedString("text_key", comment: "Says how many items (1st var) were collected out of total possible (2nd var)")
let text = String.localizedStringWithFormat(format, numberOfItems, totalNumberOfItems)
Which gives
"Collected 2 out of 10"
However I can imagine that in some languages it would be more natural to have these values appear in a different order resulting in a non-sensical string such as
"Out of a possible 2 items you collected 10"
I cannot find a simple way to encode this using the standard Swift library such as
"text_key" = "Out of a possible {2%d} items you collected {1%d}"
and can see this getting cumbersome hardcoding these as more values are added.
String.localizedStringWithFormat() works with “positional arguments”
%n$. In your case
"text_key" = "Out of a possible %2$d items you collected %1$d";
would do the trick.
These are documented in fprintf:
Conversions can be applied to the nth argument after the format in the argument list, rather than to the next unused argument. In this case, the conversion specifier character % (see below) is replaced by the sequence "%n$", where n is a decimal integer in the range [1,{NL_ARGMAX}], giving the position of the argument in the argument list.

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

double.parse(str) result is off by orders of magnitude

I have a weird problem in converting a string to double in .NET 3.5. Here is my code:
dbl = double.Parse(str);
When str is string with a simple double like "5.67" the result for dbl is 567.0.
I'd guess this is localisation issues and you need to use the overload that specifies a format provider.
The issue is likely that it is expecting , as a decimal separator and . as a thousand separator (and thus ignoring it in effect).
Example to reproduce possible issue:
string input = "5.67";
Console.WriteLine(Double.Parse(input, new CultureInfo("en-gb")));
Console.WriteLine(Double.Parse(input, new CultureInfo("de-de")));
This outputs:
5.67
567
I'm just editing Chris's answer:
value = "5.67";
double out;
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = CultureInfo.CreateSpecificCulture("en-GB");
Console.WriteLine(Double.TryParse(value, style, culture, out number)?number:0);

matlab saving a cellarray

I have a script which does not fully work:
inputfield=input('Which field would you like to see: ','s')
if isfield(package, inputfield)
fprintf('The value of the %s field is: %c\n',inputfield,...
eval(['package.' inputfield]))
else
fprintf('Error: %s is not valid field\n', inputfield)
end
First I define a structure in matlab and then i use the script on the structure:
package=struct('item_no',123,'cost',19.99,'price',39.95,'code','g')
package =
item_no: 123
cost: 19.9900
price: 39.9500
code: 'g'
structurevalue
Which field would you like to see: cost
inputfield =
cost
The value of the cost field is: 1.999000e+001
structurevalue
Which field would you like to see: item_no
inputfield =
item_no
The value of the item_no field is: {
why cant it read value for item_no?
Try:
fprintf('The value of the %s field is: %s\n',inputfield,...
num2str(package.(inputfield)))
There were two issues with your version.
You were passing both numbers and strings into the %c field in your fprintf string. When a decimal goes in, it is interpreted as a number and displayed in full precision, which is why 19.99 got displayed as 1.999000e+001. But when an integer goes in, it gets interpreted as a character, which is why 123 got displayed as '{' (ASCII character 123). Use num2str to convert numbers to strings for display. Also, use %s for a string of any length, rather than %c for a character.
In general, it's not a good idea to use eval unless you have to. In this case, it's more convenient to use inputfield as a dynamic field name of package.