Showing price 2 decimal places with comma angular7 / ionic4 - angular7

Hi from the api i return prices such as 1.00 or 2.00 but in the template i want to show this as €1,00 or €2,00. Im doing following:
<ion-icon name="pricetag" color="secondary"></ion-icon> Minimale Kbestelling <B>{{item.minimal_order | currency:'EUR'}}</B>
How can i replace the . for a comma? I know the thousand seperator uses a comma but i want to show only comma's how can i do this ?
i dont see a option to do this:
https://angular.io/api/common/CurrencyPipe

The Angular internationalization page (https://angular.io/guide/i18n) provides a wealth of information about localizing your app. If you want to use a comma radix instead of a decimal, you can choose an appropriate locale and then include it as a parameter for your currency pipe configuration.
The fourth parameter to the currency pipe is the locale to use for display, which determines whether a comma or a period is used as the radix symbol. For example, the fr locale might look like this:
https://codesandbox.io/s/k203o9nr07
import { Component } from "#angular/core";
import { registerLocaleData } from "#angular/common";
import localeFr from "#angular/common/locales/fr";
registerLocaleData(localeFr, "fr");
#Component({
selector: "app-root",
template: "<div>My number is {{this.value | currency:'EUR':'symbol':'':'fr'}}</div>"
})
export class AppComponent {
value = 1234.5678;
}
Sources:
https://angular.io/api/common/CurrencyPipe#parameters
https://stackoverflow.com/a/52440415/1941654

Related

How to format decimal places in Aspose.Word Template?

I want all numerical data to be formatted with 2 decimal places.
Is there a way to set this in the template word file (where I output the variable value via
<<[variableName] >>
), or even globally?
To format a numeric expression result, you can specify a format string as an element of the corresponding expression tag.
<<[variableName]:"0.##">>
See the following article for more information:
https://docs.aspose.com/words/net/outputting-expression-results/

Formatting a currency depending upon the currency code selected regardless of device's locale (Swift)

I am trying to format currencies depending on the currency selected by the user. If no currency is selected, then device's current locale is used for formatting. however, I am having issues:
I am using a number formatter to format the double to currency string.
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = ""
if currencyCode != nil {
formatter.currencyCode = currencyCode
}
let amount = Double(amt/100) + Double(amt%100)/100
return formatter.string(from: NSNumber(value: amount))
}
The currencyCode is basically the currency the user has selected. However, if say the user selects EURO, the formatting is pretty much the same as for USD, meaning that it is not respecting the currency selected. I know that we cannot possibly create a Locale out of currencyCode since EUR is used in 26 different countries so it's impossible to derive the correct locale.
Also since I am using a format which basically fills the decimals position, then ONES, Tenths and so on and some currencies don't support decimal positions for example, PKR (Pakistani Ruppee) so how can I cater for that?
So my question is how can I format a currency correctly regardless of which device locale is selected.
If my device locale is say USD and I create a EUR list, I would like all payments inside the list to be in EUR format.
So if in USD a price is $3,403.23 in EUR it should be € 3 403,23.
Any advice on how I should go about formatting? Thanks!
In short
The locale settings related to currency are of two kinds:
Currency dependent: these are related to the monetary value and depend only on the currency and remain valid wherever you use that currency. This is only the international ISO code and the number of decimals, as defined by ISO 4217.
Cultural settings: these depend on the usages and practices related to the language and the country of the users and not directly to the currency. Typically, it's the position of the currency code or symbol relatively to the value, as well as the decimal and thousand separators.
Fortunately, Swift makes very well the difference. Here some code, that allows you to adapt the currency dependent settings, without ever touching to the cultural settings that important for the user. I'll also explain why you shouldn't change all the local settings.
The code
Here the demo code, with a couple of representative currencies:
let value: Double = 1345.23
for mycur in ["USD", "TND", "EUR", "JPY" ] {
let myformatter = NumberFormatter()
myformatter.numberStyle = .currencyISOCode
let newLocale = "\(Locale.current.identifier)#currency=\(mycur)" // this is it!
myformatter.locale = Locale(identifier:newLocale)
print ("currency:\(mycur): min:\(myformatter.minimumFractionDigits) max:\(myformatter.maximumFractionDigits)"
print ("result: \(myformatter.string(from: value as NSNumber) ?? "xxx")")
}
For a representative demo, I've used :
the USD and the EUR, which, like most currencies can be divided in 100 sub-units (the cents),
the TND (Tunesian Dinar), which, like a handfull of other dinar-currencies, can be divided in 1000 sub-units (the millims),
the JPY(Japanese Yen), which could in the past be divided into sub-units (the sens) of such a small value that the Japanese government decided not to use them anymore. This is why there are no decimals anymore for JPY amounts.
The results
For the user, will benefit from the principle of least astonishment, and see the decimal and thousand separators and the positioning he/she is used-to.
in my current locale (in my language currency code is to the right, decimals are separated by a comma, and thousands with a hard space) the result will be:
cur:USD: min:2 max:2 result: 1  345,23 USD
cur:TND: min:3 max:3 result: 1  345,230 TND
cur:EUR: min:2 max:2 result: 1  345,23 EUR
cur:JPY: min:0 max:0 result: 1  345 JPY
But if you'd usually work in an English speaking environment, for example in a US culture, you'd get:
cur:USD: min:2 max:2 result: USD 1,345.23
cur:TND: min:3 max:3 result: TND 1,345.230
cur:EUR: min:2 max:2 result: EUR 1,345.23
cur:JPY: min:0 max:0 result: JPY 1,345
How it works:
The trick of the code is to create a new locale, by just changing the currency settings, but leaving intact all other country and language dependent parameters.
let newLocale = "\(Locale.current.identifier)#currency=\(mycur)" // this is it!
myformatter.locale = Locale(identifier:newLocale)
Why you should not fully implement what you wanted
If you would start to adapt the positioning to take the practice of the language of the country the currency is originating from, you might irritate the users who no longer see the currency code where they expect them. Fortunately, it will not create a real confusion.
Example: the EUR is the currency of countries with very different cultures. The rule about positioning of the currency or the currency symbol was therefore defined to be dependent on the language of the text in which the amount appears. Official reference
Now, if you would start to adopt thousand and decimal separators of another language or country because it's the currency's home country, this would create a real confusion, especially for smaller amounts. Moreover, it's not always possible.
Example: In Canada the same currency amount is written with comma decimal separator by French-speaking Canadians, but dot decimal separator by english-speaking Canadians. This clearly shows it's not the currency that determines the separators to use, but the language of the user.
You should therefore be respectful of the user's settings in this regard, and only adapt the currency specific settings.
You can dynamically match Locales to currency codes, since you can create all supported Locales from the availableIdentifiers property of Locale and then you can check their currencyCode property to match the currency code your user input.
extension Locale: CaseIterable {
public static let allCases: [Locale] = availableIdentifiers.map(Locale.init(identifier:))
}
public extension Locale {
init?(currencyCode: String) {
guard let locale = Self.allCases.first(where: { $0.currencyCode == currencyCode }) else { return nil }
self = locale
}
}
Locale(currencyCode: "EUR") // es_EA
Locale(currencyCode:"GBP") // kw_GB
However, as you can see, this can return exotic locales, which might not necessarily give your desired formatting.
I would rather suggest hardcoding the desired Locale for each currency code that your app supports, that way you can be 100% sure the formatting always matches your requirements. You can also mix the two approaches and have hardcoded Locales for the well-known currency codes, but use the dynamic approach for more exotic currency codes that you have no hard requirement over how they should be formatted.

How to add serializer in dart to convert iso 8601 to datetime object?

In dart I want to do this:
var s = "2018-11-23T04:25:41.9241411Z"; // string comes from a json but represented here for simplicity like this
var d = DateTime.parse(s);
but it throws a null.
Dart can't seem to parse iso 8601 date time formats. I've found a custom serializer called "Iso8601DateTimeSerializer" but how do I add it to my flutter app?
links: https://reviewable.io/reviews/google/built_value.dart/429#-
The instructions here only indicate adding it to dart using "SerializersBuilder.add" but I'm a newbie and cant find out how?
link:
https://pub.dartlang.org/documentation/built_value/latest/iso_8601_date_time_serializer/Iso8601DateTimeSerializer-class.html
The problem is that Dart's DateTime.parse only accepts up to six digits of fractional seconds, and your input has seven.
... and then optionally a '.' followed by a one-to-six digit second fraction.
You can sanitize your input down to six digits using something like:
String restrictFractionalSeconds(String dateTime) =>
dateTime.replaceFirstMapped(RegExp(r"(\.\d{6})\d+"), (m) => m[1]);
Maybe the parse function should just accept more digits, even if they don't affect the value.
Just to add to Irn's answer. You need to add some escapes for the regex to work properly.
String restrictFractionalSeconds(String dateTime) =>
dateTime.replaceFirstMapped(RegExp("(\\.\\d{6})\\d+"), (m) => m[1]);
You need to add it to the serializers builder.
Example:
#SerializersFor(models)
final Serializers serializers = (_$serializers.toBuilder()
..addPlugin(StandardJsonPlugin())
..add(Iso8601DateTimeSerializer()))
.build();

Add class for number_with_precision

I have a code, which shows price:
def value
h.number_with_precision(object.value, precision: 2,strip_insignificant_zeros: false)
end
And i put this value in haml: %b= #{number.value}
For example: showing price "1234.02" inside <b/> and I need some styles to ".02". How to put precision inside span?
EDIT:
Ruby string have formatter built in. No need to use any class.
Just use "%.2f" % #{number.value}
You have to split number.value with '.' as separator, and use it like
full_value = number.value.to_s.split('.')
haml: %b #{full_value[0]}.
%span #{full_value[1]}
As you are not stripping insignificant zeroes you will always have 3 digits at the end you need to format (assuming you're including the decimal place).
You can do
number.value.to_s[0..-4]
Which will give you all characters in the string apart from the last 3, and then
number.value.to_s.last(3)
To return the part you want to format separately
If you don't want to format the decimal point, and just need the last 2 characters separated:
number.value.to_s[0..-3]
number.value.to_s.last(2)
You can then format these as needed

Swift, iOS: How to convert a string containing number and character (i.e ',' or ',') into number?

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)")

Resources