How to display an int without commas? - swift

I have a list of Text views that include a year saved as an int. I'm displaying it in an interpolated string:
Text("\($0.property) \($0.year) \($0.etc)")
The problem, it adds a comma to the int, for example it displays 1,944 instead of the year 1944. I'm sure this is a simple fix but i've been unable to figure out how to remove the comma. Thanks!

There is explicit Text(verbatim:) constructor to render string without localization formatting, so a solution for your case is
Text(verbatim: "\($0.property) \($0.year) \($0.etc)")

Use Text(String(yourIntValue)) if you use interpolation you need to cast it as a string directly. If you allow the int to handle it, it shows with a ,.
So to recap.
let yourIntValue = 1234
Text(String(yourIntValue)) // will return `1234`.
Text("\(yourIntValue)") // will return `1,234`.

I use the built-in format parameter. It's useful for formatting well beyond just this one specific usage (no commas).
Text("Disk Cache \(URLCache.shared.currentDiskUsage,
format: .number.grouping(.never))"))

Related

Using the toInteger function with locale and format parameters

I've got a dataflow with a csv file as source. The column NewPositive is a string and it contains numbers formatted in European style with a dot as thousand seperator e.g 1.019 meaning 1019
If I use the function toInteger to convert my NewPositive column to an int via toInteger(NewPositive,'#.###','de'), I only get the thousand cipher e.g 1 for 1.019 and not the rest. Why? For testing I tried creating a constant column: toInteger('1.019','#.###','de') and it gives 1019 as expected. So why does the function not work for my column? The column is trimmed and if I compare the first value with equality function: equals('1.019',NewPositive) returns true.
Please note: I know it's very easy to create a workaround by toInteger(replace(NewPositive,'.','')), but I want to learn how to use the toInteger function with the locale and format parameters.
Here is sample data:
Dato;NewPositive
2021-08-20;1.234
2021-08-21;1.789
I was able to repro this and probably looks to be a bug to me . I have reported this to the ADF team , will let you know once I hear back from them . You already have a work around please go ahead that to unblock yourself .

How to display Icon from package using name from String?

I want to display Icon based on it's name parsed from external source. Now i have several newsfeeds integrated in app, like this:
myPages.add(new Subpage(0, "Main", FontAwesome5Regular.newspaper, "http://url.one"));
myPages.add(new Subpage(1, "Buses", MaterialCommunityIcons.bus_multiple, "http://url.one"));
where 3-d argument of SubPage constructor is IconData. 
I want to generate so much pages as needed, based on CSV. I want to place in CSV lines like
0, Main, FontAwesome5Regular.newspaper, "http://url.one"
1, Buses, MaterialCommunityIcons.bus_multiple, "http://url.two"
I have no problems with parsing csv, but I don't understand how to convert parsed String "FontAwesome5Regular.newspaper" to IconData needed by constructor of Subpage.
It would be great to get solution without async/await, catching error, etc, cause I'm really sure, that CSV contains no errors, all strings are valid, all classes are available
Thank you for any ideas!
You could use 'dart:mirrors' library for that, but, unfortunately, library isn't available in flutter, so you can't access classes' static properties using their names as string. You can do it like this:
IconData getIconData(String str) {
switch (str) {
case "FontAwesome5Regular.newspaper": return FontAwesome5Regular.newspaper;
case "MaterialCommunityIcons.bus_multiple": return MaterialCommunityIcons.bus_multiple;
default: return null;
}
}
great workaroud from Richard Heap:
Can you change your CSV? Let's say you want to send an umbrella icon. Rather than "MaterialIcons.beach_access" send "MaterialIcons" in one column and "60222" in another. Parse the 60222 into a int: var codePoint = int.parse(cp); and make your icon as var icon = IconData(codePoint, fontFamily: ff);
– Richard Heap 2 hours ago

Running operations on numbers with commas in Swift3

If I have a number that is over 1,000, so that it has a comma in it, how can I either strip out the commas, or convert this number into a Double, so that I can run mathematical operations on it?
Right now, I have the following code:
let oldBFTally: Double = Double(plBFTally.text!)!
let newBFTally: Double = round(1000 * (rawValue + oldBFTally) / 1000)
This code works great, as long as the number is under 1000. But, being that I am formatting the number as text, so that it has commas (ie: 1,234.56), whenever I try to run that first line, it errors out, saying: "fatal error: unexpectedly found nil while unwrapping an Optional value".
Any ideas what I can do to navigate around this issue?
But, being that I am formatting the number as text, so that it has commas (ie: 1,234.56)
You're trying to tackle the problem in the wrong way. If you're generating this string in the first place, then if you want to perform mathematical operations on the number, you shouldn't be displaying it as a string in the UI, then trying to go backwards from the UI back to a number. That's misusing your presentation layer as your data model.
Instead of trying to go back and forth between the UI, use the original value you generated the string from.
#Jim is correct; your text field should simply contain a textual representation of your internal variable, so you shouldn't need to convert back to a double, but for reference, you can use a NumberFormatter
import Foundation
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
if let number = formattter.number(from:"10,000") {
print(number.doubleValue)
}

JQuery Wildcard for using atttributes in selectors

I've research this topic extensibly and I'm asking as a last resort before assuming that there is no wildcard for what I want to do.
I need to pull up all the text input elements from the document and add it to an array. However, I only want to add the input elements that have an id.
I know you can use the \S* wildcard when using an id selector such as $(#\S*), however I can't use this because I need to filter the results by text type only as well, so I searching by attribute.
I currently have this:
values_inputs = $("input[type='text'][id^='a']");
This works how I want it to but it brings back only the text input elements that start with an 'a'. I want to get all the text input elements with an 'id' of anything.
I can't use:
values_inputs = $("input[type='text'][id^='']"); //or
values_inputs = $("input[type='text'][id^='*']"); //or
values_inputs = $("input[type='text'][id^='\\S*']"); //or
values_inputs = $("input[type='text'][id^=\\S*]");
//I either get no values returned or a syntax error for these
I guess I'm just looking for the equivalent of * in SQL for JQuery attribute selectors.
Is there no such thing, or am I just approaching this problem the wrong way?
Actually, it's quite simple:
var values_inputs = $("input[type=text][id]");
Your logic is a bit ambiguous. I believe you don't want elements with any id, but rather elements where id does not equal an empty string. Use this.
values_inputs = $("input[type='text']")
.filter(function() {
return this.id != '';
});
Try changing your selector to:
$("input[type='text'][id]")
I figured out another way to use wild cards very simply. This helped me a lot so I thought I'd share it.
You can use attribute wildcards in the selectors in the following way to emulate the use of '*'. Let's say you have dynamically generated form in which elements are created with the same naming convention except for dynamically changing digits representing the index:
id='part_x_name' //where x represents a digit
If you want to retrieve only the text input ones that have certain parts of the id name and element type you can do the following:
var inputs = $("input[type='text'][id^='part_'][id$='_name']");
and voila, it will retrieve all the text input elements that have "part_" in the beginning of the id string and "_name" at the end of the string. If you have something like
id='part_x_name_y' // again x and y representing digits
you could do:
var inputs = $("input[type='text'][id^='part_'][id*='_name_']"); //the *= operator means that it will retrieve this part of the string from anywhere where it appears in the string.
Depending on what the names of other id's are it may start to get a little trickier if other element id's have similar naming conventions in your document. You may have to get a little more creative in specifying your wildcards. In most common cases this will be enough to get what you need.

Extracting data(strings) from a string large string

A long time ago I had to extract data from a string, and I went with a while loop that went through the whole string char by char extracting bits of data that I need. It wasn't very efficient but it worked.
In my latest app I would like to try and do it in the way that a good engineer would do it. Are there ways to search the string for an expression? or a sub string maybe?
For example out of the html in the string, there is a line that will contain a team name.
<td width="25%"><span class="teamname">Blue Bombers</span></td>
Is there a call I can do that would find the "teamname" and then extract the teamname from between the > <.
I could go char by char saving the last 10 chars to a string until the string equals "teamname", then keep going until i hit the > save everything i get until i again hit a <. but i guess thats taking the easy inefficient way.
Many Thanks
-Code
You can get the range of string "class" using NSRange, then do your logic... it will probably reduce the character searching..
Your code should be like follows,
if ([substring rangeOfString:#"class"].location != NSNotFound) {
// "class" was found
else {
// "class" was not found
}
If that's the only part of the string you're interested in and then just find a starting point like "teamname" via -rangeOfString:. If there's more than one occurrence then make repeated calls with -rageOfString:options:range:.
If you need more comprehensive parsing, however..
If this string is actual XHTML then you may be able to use one of the various XML parsers, e.g. TouchXML, and then find what you need via DOM lookups. However if (as seems likely) it's not pure XHTML then this is unlikely to help. In that case you might try loading up the HTML in an offscreen UIWebView and using JavaScript calls to find specific elements.