I need a print function that writes Loop i / round, where both values i and round have to have at least four digits (12 -> 0012). It must have the format-method too.
I found the paste formatC and other ways to add leading zeroes but I can't make them work for this case..
It needs to be like this:
print('Loop {} / {}'.format('i', 'round'))
But with four digit numbers as I said.
number_str = str(a_number)
zero_filled_number = number_str.zfill(4)
a_number is 12.
zero_filled_number will give you 0012
Use print("{:02d}".format(1)) as found in this answer.
Related
I'm making a list for buying groceries in Google Sheets and have the following value in cell B4.
0.95 - Lemon Juice
2.49 - Pringle Chips
1.29 - Baby Carrots
9.50 - Chicken Kebab
What I'm trying to do is split using the dash character and combine the costs (0.95+2.49+1.29+9.50).
I've tried to use Index(SPLIT(B22,"-"), 7) and SPLIT(B22,"-") but I don't know how to use only numbers from the split string.
Does someone know how to do this? Here's a sample sheet.
Answer
The following formula should produce the result you desire:
=SUM(ARRAYFORMULA(VALUE(REGEXEXTRACT(SPLIT(B4,CHAR(10)),"(.*)-"))))
Explanation
The first thing to do is to split the entry in B4 into its component parts. This is done by using the =SPLIT function, which takes the text in B4 and returns a separate result every time it encounters a specific delimiter. In this case, that is =CHAR(10), the newline character.
Next, all non-number information needs to be removed. This is relatively easy in your sample data because the numbers always appear to the left of a dash. =REGEXEXTRACT uses a regular expression to only return the text to the left of the dash.
Before the numbers can be added together, however, they must be converted to be in a number format. The =VALUE function is used to convert each result from a text string containing a number to an actual number.
All of this is wrapped in an =ARRAYFORMULA so that =VALUE and =REGEXEXTRACT parse each returned value from =SPLIT, rather than just the first.
Finally, all results are added together using =SUM.
Functions used:
=CHAR
=SPLIT
=REGEXEXTRACT
=VALUE
=ARRAYFORMULA
=SUM
Firstly you can add , symbols start and ends of numbers with below code:
REGEXREPLACE(B4,"([0-9\.]+)",",$1,")
Then split it based of , sign.
SPLIT(A8, ",")
Try below formula (see your sheet)-
=SUM(ArrayFormula(--REGEXEXTRACT(SPLIT(B4,CHAR(10)),"-*\d*\.?\d+")))
Is there a simple way to print a number with either one decimal place or none?
I've searched the net for a method to do that but all of them try to always have a zero after the decimal point..
I want 3.0 to be printed as just 3, and 3.5 to be printed as 3.5.
I tried print('{:.1f}'.format(num)) but this prints 3.0
You have not specified the programming language, so I will provide an answer in pseudocode.
Using if-else
printWithOneOrNoDecimals(n)
if (isNumberInteger(n))
printWithoutDecimals(n)
else
printNumberWithOneDecimal(n)
isNumberInteger(n)
return round(n) == n
The method round(n) should round the number, for example 2.4 to 2. Because 2.4 != 2, isNumberInteger(2.4) would return false and the else statement is exectuted.
Now you can define different formats for printing numbers with or without decimal in printNumberWithOneDecimal and printWithoutDecimals.
Using “right trim” or “right strip”
Another way to achieve the result is to first make the number a string (maybe formatting it to have one decimal) and then “trimming” or “stripping” it from the right, first “all” zeros (in your case at most one) and then the decimal point (if any on the right). Note: trim or strip methods do not give an error if there’s nothing to trim/strip.
I guess that in Python it would be:
'{:.1f}'.format(num).rstrip('0').rstrip('.')
Happy coding, good luck!
I have a question regarding a volume calculation formula. We use Lua formulae embedded in pharmacy labels. One enables us to calculate the volume of drug from the entered dose where we use either %0, %1, or %2, depending on the drug, to calc to the required number of decimal places, . However even if we have defined %2 for a particular label design/drug, for some doses if the result obtained ends up as .00, for best practice it is best not to show the trailing zeroes, is there a line we can add to the formula so that the trailing zeroes are not shown
lua
Dose = Label.TextFromTag("Dose")
Concentration = Label.TextFromTag("CONC")
volume = string.format("%.2f", Dose / Concentration)
return volume
Remove the trailing zeros explicitly with
return (volume:gsub("0+$",""))
Use this only if the format is not %.0f.
Trying to work out how to parse out phone numbers that are left in a string.
e.g.
"Hi Han, this is Chewie, Could you give me a call on 02031234567"
"Hi Han, this is Chewie, Could you give me a call on +442031234567"
"Hi Han, this is Chewie, Could you give me a call on +44 (0) 203 123 4567"
"Hi Han, this is Chewie, Could you give me a call on 0207-123-4567"
"Hi Han, this is Chewie, Could you give me a call on 02031234567 OR +44207-1234567"
And be able to consistently replace any one of them with some other item (e.g. some text, or a link).
Am assuming it's a regex type approach (I'm already doing something similar with email which works well).
I've got to
text.scan(/([^A-Z|^"]{6,})/i)
Which leaves me a leading space I can't work out how to drop (would appreciate the help there).
Is there a standard way of doing this that people use?
It also drops things into arrays, which isn't particularly helpful
i.e. if there were multiple numbers.
[["02031234567"]["+44207-1234567"]]
as opposed to
["02031234567","+44207-1234567"]
Adding in the third use-case with spaces is difficult. I think the only way to successfully meet that acceptance criteria would be to chain a #gsub call on to your #scan.
Thus:
text.gsub(/\s+/, "").scan(/([^A-Z|^"|^\s]{6,})/i)
The following code will extract all the numbers for you:
text.scan(/(?<=[ ])[\d \-+()]+$|(?<=[ ])[\d \-+()]+(?=[ ]\w)/)
For the examples you supplied this results in:
["02031234567"]
["+442031234567"]
["+44 (0) 203 123 4567"]
["0207-123-4567"]
["02031234567", "+44207-1234567"]
To understand this regex, what we are matching is:
[\d \-+()]+ which is a sequence of one or more digits, spaces, minus, plus, opening or closing brackets (in any order - NB regex is greedy by default, so it will match as many of these characters next to each other as possible)
that must be preceded by a space (?<=[ ]) - NB the space in the positive look-behind is not captured, and therefore this makes sure that there are no leading spaces in the results
and is either at the end of the string $, or | is followed by a space then a word character (?=[ ]\w) (NB this lookahead is not captured)
This pattern will get rid of the space but not match your third case with spaces:
/([^A-Z|^"|^\s]{6,})/i
This is what I came to in the end in case it helps somebody
numbers = text.scan(/([^A-Z|^"]{6,})/i).collect{|x| x[0].strip }
That gives me an array of
["+442031234567", "02031234567"]
I'm sure there is a more elegant way of doing this and possibly you'd want to check the numbers for likelihood of being phonelike - e.g. using the brilliant Phony gem.
numbers = text.scan(/([^A-Z|^"]{6,})/i).collect{|x| x[0].strip }
real_numbers = numbers.keep_if{|n| Phony.plausible? PhonyRails.normalize_number(n, default_country_code: "GB")}
Which should help exclude serial numbers or the like from being identified as numbers. You'll obviously want to change the country code to something relevant for you.
Found another question that seemed to be solved by using .sprintf('%02d', 1) to solve this, but I get: 'private method `sprintf' called for 7:Fixnum'.
Does this mean sprintf cant be called on an integer or am I getting it wrong in the calling?
Just looking to pad single digit returns with a leading 0.
Thanks in advance for any help on this!
You might want to try using sprintf like this:
sprintf('%02d', 1)
# => "01"
ie
sprintf('%02d', model.count)
Not calling .sprintf on the number but rather inputing it as a parameter into sprintf()
you may want to try "0#{num}"[-2..-1] or "%02d" % 1