number.toLocaleString() is not working in react-native, can anyone suggest better way to format currency in react-native,
code goes here
formatMoney(number) {
if(number===undefined||number===null)
{
return 0
}
else
{
var n=number.toString
var obj={
style:'currency',
currency:'GBP'
}
'use strict'
return n.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' });
}
}
You want to use the Number.toLocaleString function, therefore you need to make sure that you are calling it on a number and not on a string. See example below:
var n = 5555;
//var n=number.toString(); remove this line
var obj={
style:'currency',
currency:'GBP'
}
formatted = n.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' });
console.log("formatted",formatted);
You can use this library react-number-format. It has these features
Prefix, suffix and thousand separator.
Custom format pattern.
Masking.
Custom formatting handler.
Format number in an input or format as a simple text
Sample usage
<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />
Output : $2,456,981
Related
I have a number input that pops up a "numeric" text input in React Native.
In many locales this brings up a numeric pad with a comma for decimal separation, instead of a dot. This results in inputs like "100,1" instead of "100.1".
JavaScript's Number(value) only works with dot decimals, not commas. How can I determine the user's current format in order to properly parse the input?
This function will parse a decimal input based on the current locale, using react-native-localize:
import { getNumberFormatSettings } from "react-native-localize";
export function parseLocaleNumber(stringNumber: string) {
const { decimalSeparator, groupingSeparator } = getNumberFormatSettings();
return Number(
stringNumber
.replace(new RegExp(`\\${groupingSeparator}`, "g"), "")
.replace(new RegExp(`\\${decimalSeparator}`), "."),
);
}
For good measure, this complementary function provides toFixed functionality based on locale:
export function toFixedLocale(value: number, numDigits: number) {
const standardFixedString = value.toFixed(numDigits);
const { decimalSeparator } = getNumberFormatSettings();
if (decimalSeparator === ",") {
return standardFixedString.replace(".", ",");
} else {
return standardFixedString; // Locale matches JavaScript default
}
}
(parseLocaleNumber based on https://stackoverflow.com/a/42213804/152711)
I'm using DataTables 1.10.5. When I'm trying to sort on dates using the recommended moment.js (as per http://datatables.net/blog/2014-12-18), thinks work fine:
http://jsfiddle.net/9gohzd9t/1/
However, when I add a link (a href) to that date, it sorts on the link instead of the date:
http://jsfiddle.net/dnsL2oc4/1/
Any idea on how to properly fix this without too much hacking around?
The problem lies in the unshift method of datetime-moment.js. Moment tries to convert 12-01-2001 to a valid date in the given "DD-MM-YYYY"-Format, which it can't obviously. So you have to strip the html away from the date, probably with a function like this:
function strip(html) {
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
And then strip the string in the unshift method (Replace datetime-moment.js with the code below):
$.fn.dataTable.moment = function (format, locale) {
var types = $.fn.dataTable.ext.type;
// Add type detection
types.detect.unshift(function (d) {
return moment(strip(d), format, locale, true).isValid() ?
'moment-' + format :
null;
});
// Add sorting method - use an integer for the sorting
types.order['moment-' + format + '-pre'] = function (d) {
return moment(strip(d), format, locale, true).unix();
};
};
I am doing some processing across iterations in a release and I want to find out what the teams velocity was at that point in time, is there any way to use the lookback API or otherwise get the information for that period?
i.e. the Rally generated velocity at that time or manually calculate the last 10 or all time velocity measures?
So, based on the responses below I have ended up with this code:
_getVelocity: function() {
this.logger.log("_getVelocity");
var me = this;
var deferred = Ext.create('Deft.Deferred');
Ext.Array.each(this.iterations,function(iteration){
iteration.PlanEstimate = 1;
me.logger.log("Fetching velocity for iteration", iteration.Name);
var start_date_iso = Rally.util.DateTime.toIsoString(iteration.StartDate);
var end_date_iso = Rally.util.DateTime.toIsoString(iteration.EndDate);
var type_filter = Ext.create('Rally.data.lookback.QueryFilter', {
property: '_TypeHierarchy',
operator: 'in',
value: this.show_types
});
var date_filter = Ext.create('Rally.data.lookback.QueryFilter', {
property: '_ValidFrom',
operator: '>=',
value:start_date_iso
}).and(Ext.create('Rally.data.lookback.QueryFilter', {
property: '_ValidFrom',
operator: '<=',
value:end_date_iso
}));
var filters = type_filter.and(date_filter);
me.logger.log("Filter ", filters.toObject());
Ext.create('Rally.data.lookback.SnapshotStore',{
autoLoad: true,
filters: filters,
fetch: ['FormattedID','PlanEstimate','ScheduleState'],
hydrate: ['ScheduleState'],
listeners: {
scope: this,
load: function(store,it_snaps,successful) {
if ( !successful ) {
deferred.reject("There was a problem retrieving changes");
} else {
me.logger.log(" Back for ", it_snaps.length, it_snaps);
deferred.resolve(it_snaps);
}
}
}
});
});
deferred.resolve([]);
return deferred;
},
The shape of this code and the filters etc is lifted from another function in the same app that IS working, however this one is NOT working, I get the following errors:
Uncaught TypeError: Cannot read property 'Errors' of null
GET https://rally1.rallydev.com/analytics/v2.0/service/rally/workspace/99052282…ScheduleState%22%5D&pagesize=20000&start=0&jsonp=Ext.data.JsonP.callback49 400 (Bad Request)
Since LookbackAPI gives historic data, you may query stories at the specific point of time and get number of points completed at that time. There is no Rally generated velocity, so this has to be accessed and summed up manually. For example, I have iteration that started on August 7 and ended on August 14, but if I want data from August 10 I use:
https://rally1.rallydev.com/analytics/v2.0/service/rally/workspace/1234/artifact/snapshot/query.js?find={"Iteration":5678,"_TypeHierarchy":"HierarchicalRequirement",_ValidFrom:{$gte:"014-08-10",$lte:"2014-08-14"}}&fields=['FormattedID','ScheduleState','PlanEstimate']&hydrate=['ScheduleState']
UPDATE: As far as the code you posted, change
var start_date_iso = Rally.util.DateTime.toIsoString(iteration.StartDate)
var end_date_iso = Rally.util.DateTime.toIsoString(iteration.EndDate);
to
var start_date_iso = Rally.util.DateTime.toIsoString(iteration.get('StartDate'),true);
var end_date_iso = Rally.util.DateTime.toIsoString(iteration.get('EndDate'),true);
I replicated the bad request error with your syntax, and after changing it to this format it worked: iteration.get('StartDate'),true
App source code is in this repo.
Currently extjs numberfield is allowing '-' hyphen otherthan numbers into the field. how to restrict that from typing? if i give custom vtype validation it is checking only after i submit that.
use autoStripChars and remove hyphen from allowed in initComponent. corrected code below.
autoStripChars: true,
initComponent: function() {
var me = this,
allowed;
me.callParent();
me.setMinValue(me.minValue);
me.setMaxValue(me.maxValue);
// Build regexes for masking and stripping based on the configured options
if (me.disableKeyFilter !== true) {
allowed = me.baseChars + '';
if (me.allowDecimals) {
allowed += me.decimalSeparator;
}
/* removed code
if (me.minValue < 0) {
allowed += '-';
}
*/
allowed = Ext.String.escapeRegex(allowed);
me.maskRe = new RegExp('[' + allowed + ']');
if (me.autoStripChars) {
me.stripCharsRe = new RegExp('[^' + allowed + ']', 'gi');
}
}
}
You need to create custom VType. VType validation is called after any change in the textfield and you have ability to configure what characters are allowed to be entered:
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.form.field.VTypes
Take a look at xxxMask property.
You could also use a regular Textfield with a maskRe config.
maskRe: /[0-9]/
Similar to #lagnat's reply which is a whitelist you can blacklist characters using stripCharsRe config.
stripCharsRe: /-/
If you are wanting to restrict negative values.
minValue: 0
{
minValue: 0,
autoStripChars: true,
allowExponential: false
}
I have a dijit.form.NumberTextBox input field that starts out with these parms:
new dijit.form.NumberTextBox({
id: din1,
style: "width:60px",
constraints: {
places: 0,
pattern: '######'
}
},
din1);
Everything works great..My question is I would like to change 'places' and 'pattern' parms on the fly. So I wrote this to change 'places' and 'patterns' parms:
var myFldObj = dijit.byId(din1);
if (myFldObj) {
var myConstObj = myFldObj.attr('constraints');
if (myConstObj) {
myConstObj.places = 2;
myConstObj.pattern = '#####.0';
}
}
So, after I show the form again, I'd expect the entry field to allow 2 decimal places but the form still acts like places=0 and pattern='######'. When I check the values of 'places' and 'pattern' I get what I'd expect (2 and #####.0). My question:
Can you change these values on the fly??
OR
Do you have to destroy the original dijit object and recreate with new parms??
Thx!!
So, here is what worked for me:
First, I think this is a bug because an input field that starts out like
new dijit.form.NumberTextBox({
id: "fieldID",
style: "width:60px",
constraints: {
places: 0
}
},
"fieldID");
that is then changed on the fly with code like:
NOTE: ntbArry - Array of dijit.form.NumberTextBox objs tied to a html
input tag id.
for (var x=0;x < ntbArry.length;x++) {
var handle = ntbArry[x];
if (handle) {
handle.attr('constraints').places = 2;
handle.attr('constraints').pattern = '#####.0#';
}
}
Does not exhibit the same behavior as a field created this way (no constraints mods on the fly):
new dijit.form.NumberTextBox({
id: "fieldID",
style: "width: 60px",
constraints: {
places: 2,
pattern: '#####.0#'
}
},
"fieldID");
It's close in behavior but every time you type a decimal point, the error message pops up stating invalid entry. This message doesn't pop up when typing the decimal point on a field that was originally created with the constraints places=2 and pattern '#####.0#'.
So, to get original behavior I wanted:
fieldIDEvents is an array of dojo events tied to NumberTextBox fields.
Before continuing disconnect dojo events
for (var x=0;x < fieldIDEvents.length;x++) {
var handle = fieldIDEvents[x];
if (handle) {
dojo.disconnect(handle);
}
}
then destroy the NumberTextBox dojo objects
for (var x=0;x < ntbArry.length;x++) {
var handle = ntbArry[x];
if (handle) {
handle.destroy();
ntbArry[x] = null;
}
}
Next, place the input tag back into the html because it gets destroyed:
NOTE: tdtag and an id on a html td tag which should contain the input tag.
var fld1 = this.document.getElementById("tdtag");
if (fld1) {
//alert("\""+fld1.innerHTML+"\"");
fld1.innerHTML = "<input id=\"fieldID\">";
}
Now, create the NumberTextBox object again:
ntbArry[0] = new dijit.form.NumberTextBox({
id: "fieldID",
style: "width: 60px",
constraints: {
places: 2,
pattern: '#####.0#'
}
},
"fieldID");
It's a few extra steps but, at least I know this is what works for me..If I'm missing something basic, let me know, it's easy to miss the small details with this stuff.
I use Dojo 1.3 and I can see that dijit.form.NumberTextBox has no pattern and places properties, but has editOptions property. So I would try to change the constraints like this:
myConstObj.editOption.places = 2;