I'm building a calculator like. Every time I press one of the number buttons of the calculator, I would like to have the label displaying the input, to concatenate the new input to the display.
Let's say I press 1 then 2 then 5 and the label displays 125. So far I was converting each number into a string and was appending them one after one. But I would like to make it "localized". So that if the locale is US, for 1,256.43 it display 1,256.43. If the locale is FR, it displays 1 256,43.
For that I was doing the same than before but to convert the number to string I was using a NSNumberFormatter. The problem is when I get the string 1 256 and I convert it into double (to then use the formatter) with NSString(string: "1 256").doubleValue I get 1 and not 1 256
What do I do wrong?
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+")))
I have a model which has a column named code, which is a combination of the model's name column and its ID with leading zeros.
name = 'Rocky'
id = 16
I have an after_create callback which runs and generates the code:
update(code: "#{self.name[0..2].upcase}%.4d" % self.id)
The generated code will be:
"ROC0016"
The code is working.
I found (%.4d" % self.id) from another project, but I don't know how it works.
How does it determine the number of zeros to be preceded based on the passed integer.
You’re using a "format specifier". There are many specifiers, but the one you’re using, "%d", is the decimal specifier:
% starts it. 4 means it should always use at least four numbers, so if the number is only two digits, it gets padded with 0s to fill in the rest of the numbers. The second % means replace 4d with whatever comes after it. So in your case, 4d is getting replaced with "0016".
sprintf has more information about format specifiers.
You can read more about String#% in the documentation also.
After the percentage sign ("%") is a decimal (".") and a number. That number is the number of total digits in the result. If the result is less than this value, additional zeros will be added.
Thus, in this first example, the result is "34" but length was set to "4". The result will have two leading zeros to fill it into four digits.
"This is test string %.4d" % 34
result => "This is test string 0034"
"I want more zeroes in my code %.7d" % 34
result => "I want more zeroes in my code 0000034"
I'm creating a Lua script which will calculate a temperature value then format this value as a 4 digit hex number which must always be 4 digits. Having the answer as a string is fine.
Previously in C I have been able to use
data_hex=string.format('%h04x', -21)
which would return ffeb
however the 'h' string formatter is not available to me in Lua
dropping the 'h' doesn't cater for negative answers i.e
data_hex=string.format('%04x', -21)
print(data_hex)
which returns ffffffeb
data_hex=string.format('%04x', 21)
print(data_hex)
which returns 0015
Is there a convenient and portable equivalent to the 'h' string formatter?
I suggest you try using a bitwise AND to truncate any leading hex digits for the value being printed.
If you have a variable temp that you are going to print then you would use something like data_hex=string.format("%04x",temp & 0xffff) which would remove the leading hex digits leaving only the least significant 4 hex digits.
I like this approach as there is less string manipulation and it is congruent with the actual data type of a signed 16 bit number. Whether reducing string manipulation is a concern would depend on the rate at which the temperature is polled.
For further information on the format function see The String Library article.
I have an double that i am converting using NSMassFormatter from kg to lb.
let massFormatter = NSMassFormatter()
var xyz = massFormatter.stringFromKilograms(10000.000)
// xyz "22,046.226 lb"
Now I want a way to extract the number from the string. Also if I change the Locale to say es (Spain) then the value becomes "10.000,000 kg" (It actually returns "10.000 kg", removing the decimal points for unknown reasons), but i want a way such that I can extract the number regardless of the locale. Is there any standard way? Like use a regrex or some function in NSNumberFormatter?
Thank you
There is no way to do that fully independent of locale. The main problem is that identical string will be interpreted differently depending on what locale it is run against.
Best solution will be to identify all the possible formats, define all possible formatters and try to get numberFromString: from each formatter - until the first one to obtain the correct result.
The other solution, if you're getting the data from user input, is to explain the correct format to users and provide them with instant validation - i.e. showing "incorrect format" error message. Some apps have used the UIKeyboardTypeNumberPad keyboard to restrict user, so that you'll have only numeric values.
Two keys to the problem, finding the localized units (the "kg") part in your example, and converting the string using localized grouping and decimal separators:
// convert mass to string
var lbs = massFormatter.stringFromKilograms(10000)
println("\(lbs)")
// get localized unit specifier and remove from formatted string
var units = massFormatter.unitStringFromKilograms(10000, usedUnit: nil)
if let range = lbs.rangeOfString(units) {
lbs.replaceRange(range, with: "")
}
// get number formatter and set it to use grouping separator (, or .)
let numberFormatter = NSNumberFormatter()
numberFormatter.usesGroupingSeparator = true
// get number back
var kg = numberFormatter.numberFromString(lbs)
println("\(kg)")
When performing calculations on large numbers, how does one properly output the result in the right String format for the end user to see? I've tried the different format specifiers for NSString and compared the results to what the iOS Calculator app shows and some of the results aren't the same. Ideally it would match the iOS Calculator results exactly.
I know it needs to be displayed in decimal format until the number is sufficiently large, and at that point it needs to be shown in scientific notation. Therefore I thought %g was the right specifier. But it doesn't match the built-in calculator for the same calculation.
[NSString stringWithFormat:#"%g", calcResult] //where calcResult is a double
Some examples:
123456.7 * 1 should display as 123456.7 but it is displayed as 123457 (puzzling!)
123456789 * 1 should display as 123456789 but it's displayed as 1.23457e+08
123456789 * 123456789 should display as 1.524158e+16 but it's displayed as 1.52416e+16
Also, how does one get the comma (or period depending on locale) to appear in the result? Are there additional specifiers one can use to get the exact format the iOS Calculator shows?