Numeric Format for No Thousands Separator - jquery-globalization

Is there a number format that would produce a localized number without the thousands separator?
Globalize.format("1000.12", "n?" )
I realize I could do:
Globalize.culture().numberFormat[","]="";
But I have some fields where I want it off and some where it should be on. For example... If the value is:
1000.123 -> Want it to show formatted to 1000,12 or 1000.12 depending on locale..But without the thousands separator.

You can use the "d" format instead of the "n" format to exclude the thousands separator.
Globalize.format(1000.12, "d");
Edit
Note that this will only work if you don't care about the decimal part.
If you care about the decimal part, as far as I know, you can't exclude the thousands separator except through one of the following methods:
Set the thousands character in the culture object to an empty string:
Globalize.culture().numberFormat[","] = "";
Globalize.format(1000.12, "n");
You could turn this into a utility function fairly easily:
function formatNumberNoThousands(num, format, culture) {
var numberFormat = Globalize.cultures[culture || Globalize.culture().name].numberFormat,
thousands = numberFormat[","];
numberFormat[","] = "";
try { return Globalize.format(num, format, culture); }
finally { numberFormat[","] = thousands; }
}
Perform a replace on the string result of the format:
Globalize.format(1000.12, "d").replace(new RegExp("\\" + Globalize.culture().numberFormat[","], "g"), "");
Which can also be easily turned into a utility function:
function formatNumberNoThousands(num, format, culture) {
return Globalize.format(num, format).replace(new RegExp("\\" + Globalize.culture(culture).numberFormat[","], "g"), "");
}
With this approach, if you know there will never be more than one thousands character in the formatted result you can remove the regexp. Otherwise if you plan on using this a lot or inside of a loop, you will want to cache the regexp and re-use it.

Related

Remove words except last one in String

I have a String with different value every time:
String words = "My name is Rob Joe";
I want to get only last word
Joe
but every time I don't know how many words the string consists of
String words = "My name is Rob Joe";
var array = words.split(" "); // <-- [My, name, is, Rob, Joe]
print(array.last); // output 'Joe'
In Flutter(Dart), you can get the last word of a string by splitting the string into an array of substrings using the split method and then accessing the last element of the resulting array. Here's an example:
String words = "My name is Rob Joe";
List<String> wordsArray = myString.split(" ");
String lastWord = wordsArray[wordsArray.length - 1];
print(lastWord); // "Joe"
Instead of splitting, you can also use substring and lastIndexOf:
final words = "My name is Rob Joe";
final lastWord = words.substring(words.lastIndexOf(" ") + 1);
print(lastWord);
If you want to find the last word, you should first properly define what a "word" is.
It's clearly obvious here, which is why it's doubly important to write it down, because something else may be just as obvious to someone else.
(Read: Nothing is obvious. Document it all!)
But let's say that a word is a maximal contiguous sequence of ASCII letters.
Then that's what you should look for.
Splitting on space characters works for this string, but won't if you have punctuation, or trailing whitespace, or any number of other complications.
I'd probably use a RegExp:
// Matches a word. If used properly, only matches entire words.
var wordRE = RegExp(r"[a-zA-Z]+");
// Assume at least one word in `words`. Otherwise need more error handling.
var lastWord = wordRe.allMatches(words).last[0]!;
This can be a little inefficient, if the string is long.
Another approach that might be more efficient, depending on the RegExp implementation, is to search backwards:
/// Captures first sequence of [a-zA-Z]+ looking backwards from end.
var lastWordRE = RegExp(r"$(?<=([a-zA-Z]+)[^a-zA-Z]*)");
var lastWord = lastWordRE.firstMatch(words)?[1]!;
If you don't want to rely on RegExps (which are admittedly not that readable, and their performance is not always predictable), you can search for letters manually:
String? lastWord(String words) {
var cursor = words.length;
while (--cursor >= 0) {
if (_isLetter(words, cursor)) {
var start = 0;
var end = cursor + 1;
while (--cursor >= 0) {
if (!_isLetter(words, prev)) {
start = cursor + 1;
break;
}
}
return words.substring(start, end);
}
}
return null;
}
bool _isLetter(String string, int index) {
var char = string.codeUnitAt(index) | 0x20; // lower-case if letter.
return char >= 0x61 /*a*/ && char <= 0x7a /*z*/;
}
But first of all, decide what a word is.
Some very real words in common sentences might contain, e.g., ' or -, but whether they matter to you or not depends on your use-case.
More exotic cases may need you to decide whether"e.g." is one word or two? Is and/or? Is i18n?
Depends on what it'll be used for.

How can i outputs result between 2 specific characters in dart String

How can i outputs result between 2 specific characters in dart String
example
String myVlue = 'helloWorld';
wanted result is : anything between 'hel' and 'ld'
so the result is 'loWor'
Note : in my case the two specific characters are fixed and Unique
How can i tell dart to do that in best way .
thanks
You could define a regular expression to catch a group from your input:
void main() {
String myValue = 'helloWorld';
RegExp regExp = RegExp(r'hel(.*)ld');
String extract = regExp.firstMatch(myValue)![1]!;
print(extract); // loWor
}

How to capitalize each word in a string using Swift iOS

Is there a function to capitalize each word in a string or is this a manual process?
For e.g. "bob is tall"
And I would like "Bob Is Tall"
Surely there is something and none of the Swift IOS answers I have found seemed to cover this.
Are you looking for capitalizedString
Discussion
A string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
and/or capitalizedStringWithLocale(_:)
Returns a capitalized representation of the receiver using the specified locale.
For strings presented to users, pass the current locale ([NSLocale currentLocale]). To use the system locale, pass nil.
Swift 3:
var lowercased = "hello there"
var stringCapitalized = lowercased.capitalized
//prints: "Hello There"
Since iOS 9 a localised capitalization function is available as capitalised letters may differ in languages.
if #available(iOS 9.0, *) {
"istanbul".localizedCapitalizedString
// In Turkish: "İstanbul"
}
An example of the answer provided above.
var sentenceToCap = "this is a sentence."
println(sentenceToCap.capitalizedStringWithLocale(NSLocale.currentLocale()) )
End result is a string "This Is A Sentence"
For Swift 3 it has been changed to capitalized .
Discussion
This property performs the canonical (non-localized) mapping. It is suitable for programming operations that require stable results not depending on the current locale.
A capitalized string is a string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators (listed under getLineStart(_:end:contentsEnd:for:)). Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings.
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercased for an example.
There is a built in function for that
nameOfString.capitalizedString
This will capitalize every word of string. To capitalize only the first letter you can use:
nameOfString.replaceRange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalizedString)
Older Thread
Here is what I came up with that seems to work but I am open to anything that is better.
func firstCharacterUpperCase(sentenceToCap:String) -> String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = sentenceToCap.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
or if I want to use this as an extension of the string class.
extension String {
var capitalizeEachWord:String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = self.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
}
Again, anything better is welcome.
Swift 5 version of Christopher Wade's answer
let str = "my string"
let result = str.capitalized(with: NSLocale.current)
print(result) // prints My String

Check if string is already a currency string?

I would like to create a function that looks at a string, and if it's a decimal string, returns it as a currency-formatted string. The function below does that, however if I pass in a string that is already formatted, it will fail of course (it expects to see a string like '25' or '25.55' but not '$15.25'
Is there a way to modify my function below to add another if condition that says "if you've already been formatted as a currency string, or your string is not in the right format, return X" (maybe X will be 0, or maybe it will be self (the same string) i'm not sure yet).
func toCurrencyStringFromDecimalString() -> String
{
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
if (self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).utf16Count == 0)
{
//If whitespace is passed in, just return 0.0 as default
return numberFormatter.stringFromNumber(NSDecimalNumber(string: "0.0"))!
}
else if (IS_NOT_A_DECIMAL_OR_ALREADY_A_CURRENCY_STRING)
{
//So obviously this would go here to see if it's not a decimal (or already contains a current placeholder etc)
}
else
{
return numberFormatter.stringFromNumber(NSDecimalNumber(string: self))!
}
}
Thank you for your help!
Sounds like you need to use NSScanner.
According to the docs, the scanDecimal function of NSScanner:
Skips past excess digits in the case of overflow, so the receiver’s
position is past the entire integer representation.
Invoke this method with NULL as value to simply scan past a decimal integer representation.
I've been mostly programming in Obj-C so my Swift is rubbish, but here's my attempt at translating the appropriate code for detecting numeric strings (as also demonstrated in this answer):
let scanner: NSScanner = NSScanner(string:self)
let isNumeric = scanner.scanDecimal(nil) && scanner.atEnd
If the string is not a decimal representation, isNumeric should return false.

In monotouch how to convert string to decimal/float?

I am converting string to Float/Decimal in monotouch but it is giving format exception. I am using Decimal.Parse(), Convert.ToDecimal(). Please give any solution for this conversion.
decimal d = Convert.ToDecimal(UIDevice.CurrentDevice.SystemVersion, CultureInfo.InvariantCulture);
decimal d = Decimal.Parse(UIDevice.CurrentDevice.SystemVersion, CultureInfo.InvariantCulture);
SystemVersion is a string with multiple dots . characters. That won't parse correctly as is into a float or a decimal.
Depending on what you want you could modify the string before parsing. E.g. if you want 7.0 out of the string 7.0.2 then you could so a substring (up to the 2nd . character).
OTOH if what you need to do is a version check (most common operation) then you only need to do this:
if (UIDevice.CurrentDevice.CheckSystemVersion (7,0)) {
// do this in iOS7+
} else {
// do this before iOS7
}
System.Version has a constructor that parses that kind of string, from 2 to 4 components, in the form of:
major.minor[.build[.revision]]
So, to parse UIDevice.CurrentDevice.SystemVersion you can do:
var version = new Version (UIDevice.CurrentDevice.SystemVersion);
if (version.Major >= 7) {
//iOS7+
} else {
// anything else
}
If you're trying to figure out a particular version, use this. Otherwise #poupou's solution is great and more iOS-minded.

Resources