React-Native number formatting - react-native

I'm currently using the react-native-globalize library to format numbers but when using:
<FormattedNumber value={10000000} useGrouping={true} />
Which is supposed to present a result like this:
> 10,000,000
But for some but reason it doesn't seem to be working at all and the output is the number with no separators.
Anyone knows how to solve this or another library I could use? (yes I have done my google research first).
Thank you guys!

You can use the method toLocaleString() provided by Javascript.
Use it as:
getFormattedNumber = number => {
let formattedNumber = Number.parseInt(number).toLocaleString('en-IN');
return formattedNumber;
}
You may use en-US based on your region.
If the above code fails in Android, try below steps:
Goto your android/app/build.gradle file
Change line def jscFlavor = 'org.webkit:android-jsc:+' to def jscFlavor = 'org.webkit:android-jsc-intl:+'
Above solution is here: https://blog.bam.tech/developer-news/formating-numbers-in-react-native

You can use this function simply.
const numberWithComma = x => {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
When you call this function:
numberWithComma(10000000)
the result should be as follows:
10,000,000
For example:
let val = 14234523;
... ...
<Text> {numberWithComma(val)} </Text>
Result:
14,234,523

numberFormat = (value) => {
var re = '\\d(?=(\\d{' + 3 + '})+' + '\\D' + ')';
var num = value.toFixed(Math.max(0, ~~2));
var str = num.replace(new RegExp(re, 'g'), '$&' + ',');
return str;
}
Use:
numberFormat(4000)
Result:
4,000.00

Related

How to remove the unwanted characters from integer array in karate framework

Below is the function and its returning the integer values with %.
def functions = []
eval for(var i=0; i<response.functions.length; i++) functions.add(response.functions[i].value)
*print functions
It's return the below output.
['2.16%','1.34%','1.32%','1.25%','0.65%','0.48%','0.42%','0.26%','0.14%','0.06%','0.03%','0%']
I want to remove the single codes and % symbol. After removing it should be like below.
[2.16,1.34,1.32,1.25,0.65,0.48,0.42,0.26,0.14,0.06,0.03,0]
Please help me to remove the extra characters from Integer array
Here you go, just do a map()
* def response = ['2.16%','1.34%','1.32%']
* def cleaned = response.map(x => x.replace('%', '') * 1)
* match cleaned == [2.16, 1.34, 1.32]
Please refer to the docs: https://github.com/karatelabs/karate#json-transforms
I am able to replace the special character, '%' in this case using below code snippet. Feel free to change the special character as required. Hope this helps.
#ReplaceChars
Scenario: Replacing the special characters
* def repalceValues =
"""
function(){
let responseVal = ['2.16%','1.34%','1.32%','1.25%','0.65%','0.48%','0.42%','0.26%','0.14%','0.06%','0.03%','0%']
const finalVal = new Array();
responseVal.forEach((val) =>{
finalVal.push(val.replace('%', ''))
})
karate.log("New Array : "+ finalVal)
}
"""
* repalceValues()

How to format money on Shopify using JavaScript

I found this Gist for money formatting on Shopify using JavaScript https://gist.github.com/stewartknapman/8d8733ea58d2314c373e94114472d44c
I placed it in my cart page and when I try:
Shopify.formatMoney(2000, '$')
I get this:
cart:2166 Uncaught TypeError: Cannot read property '1' of null
at Object.Shopify.formatMoney (cart:2166)
at <anonymous>:1:9
this is at switch(formatString.match(placeholderRegex)[1]) {
I expect to get $20.00
Do you know where the problem is?
Similar question: Shopify Buy Button Error: "cannot read property '1' of null"
The Gist content
var Shopify = Shopify || {};
// ---------------------------------------------------------------------------
// Money format handler
// ---------------------------------------------------------------------------
Shopify.money_format = "${{amount}}";
Shopify.formatMoney = function(cents, format) {
if (typeof cents == 'string') { cents = cents.replace('.',''); }
var value = '';
var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/;
var formatString = (format || this.money_format);
function defaultOption(opt, def) {
return (typeof opt == 'undefined' ? def : opt);
}
function formatWithDelimiters(number, precision, thousands, decimal) {
precision = defaultOption(precision, 2);
thousands = defaultOption(thousands, ',');
decimal = defaultOption(decimal, '.');
if (isNaN(number) || number == null) { return 0; }
number = (number/100.0).toFixed(precision);
var parts = number.split('.'),
dollars = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousands),
cents = parts[1] ? (decimal + parts[1]) : '';
return dollars + cents;
}
switch(formatString.match(placeholderRegex)[1]) {
case 'amount':
value = formatWithDelimiters(cents, 2);
break;
case 'amount_no_decimals':
value = formatWithDelimiters(cents, 0);
break;
case 'amount_with_comma_separator':
value = formatWithDelimiters(cents, 2, '.', ',');
break;
case 'amount_no_decimals_with_comma_separator':
value = formatWithDelimiters(cents, 0, '.', ',');
break;
}
return formatString.replace(placeholderRegex, value);
};
I found formatMoney function in my theme and I was able to call it and it worked.
pipelineVendor.themeCurrency.formatMoney(2000);
result: $20.00
It's probably too late for the original asker, but for anyone else looking for an answer, I believe the correct call for this function is:
Shopify.formatMoney(2000, '${{amount}}')
instead of
Shopify.formatMoney(2000, '$')
based on the comment of the gist author on Github:
It doesn’t actually care what the currency is. The first argument is
the unformatted amount. The second argument is the format, which could
be whatever you need for the currently displayed currency i.e. “£{{
amount }}”. Then pass it a new amount and new format when you change
the currency.

Using symbols in JSX and React Native

I would like to use this symbol in my React Native project.
I tried using the Unicode encoding like this:
var arrow = "U+0279C";
And in the JSX:
<Text>
{arrow}
</Text>
However, this just displays the encoding literally: U+0279C.
So any idea how can I use a symbol in JSX?
You should use the HTML code for the symbol.
<Text>
➜
</Text>
As described in notes below.. (important, quotes don't seem to work)...
Just to clarify: <Text>➜</Text> will work, but <Text>{ '➜' }</Text> will not.
Use this functions for symbols in this format: & # 1 7 4 ;
/**
* replaces /$#d\+/ symbol with actual symbols in the given string
*
* Returns given string with symbol code replaced with actual symbol
*
* #param {string} name
*/
export function convertSymbolsFromCode(name = '') {
let final = null;
if (name) {
const val = name.match(/&#\d+;/) ? name.match(/&#\d+;/)[0] : false; // need to check whether it is an actual symbol code
if (val) {
const num = val.match(/\d+;/) ? val.match(/\d+;/)[0] : false; // if symbol, then get numeric code
if (num) {
final = num.replace(/;/g, '');
}
}
if (final) {
name = name.replace(/&#\d+;/g, String.fromCharCode(final));
}
}
return name;
}
USAGE
<Text>
{convertSymbolsFromCode(this.state.unicode)}
</Text>
The provided answer did not work for me, since I was dynamically retrieving unicode hex codes from an API. I had to pass them as JavaScript into the react-native jsx code.
The following answer worked for me:
Concatenate unicode and variable
I used String.fromCodePoint(parseInt(unicode, 16)) and it worked.
Example:
const unicode = unicodeHexValueFromApi //This value equals "05D2"
return(<Text>{String.fromCodePoint(parseInt(unicode, 16))}</Text>)
<Text>{"Any character"}</Text>
This worked for me.

Cache a variable in groovy

When I try to access the len-variables at the end of the script I get this error: "Cannot iterate twice! If you want to iterate more that once, add _CACHE explicitely."
How can I fix that?
def src_str = query_string
def src_arr = src_str.split(' ')
def trg_arr = doc['my_index'].values
trg_arr_sorted = [:]
trg_arr.each {
_index['my_index'].get(it, _POSITIONS).each { pos ->
trg_arr_sorted[pos.position] = it
}
}
src_len = src_arr.length
def trg_len = trg_arr_sorted.size()
int[][] matrix = new int[src_len + 1][trg_len + 1]
(src_len + 1).times { matrix[it][0] = it }
(trg_len + 1).times { matrix[0][it] = it }
(1..src_len).each { i ->
(1..trg_len).each { j ->
matrix[i][j] = [matrix[i-1][j] + 1, matrix[i][j-1] + 1,
src_arr[i-1] == trg_arr_sorted[j-1] ? matrix[i-1][j-1] : matrix[i-1][j-1] + 1].min()
}
}
return 100 - (100 * matrix[src_len][trg_len] / max(src_len, trg_len)) // over here !!!
The code calculates a score using the levenshtein distance computed in words. It works perfect except of the scoring in the last line.
Okay problem is solved.
I explicitly had to declare cache and positions:
_index['lang'].get(it, _POSITIONS | _CACHE)
The error wasn't in the last line, but I thought so. I changed the script to debug it, but elasticsearch doesn't reload the new scipt instantly.

websql use select in to get rows from an array

in websql we can request a certain row like this:
tx.executeSql('SELECT * FROM tblSettings where id = ?', [id], function(tx, rs){
// do stuff with the resultset.
},
function errorHandler(tx, e){
// do something upon error.
console.warn('SQL Error: ', e);
});
however, I know regular SQL and figured i should be able to request
var arr = [1, 2, 3];
tx.executeSql('SELECT * FROM tblSettings where id in (?)', [arr], function(tx, rs){
// do stuff with the resultset.
},
function errorHandler(tx, e){
// do something upon error.
console.warn('SQL Error: ', e);
});
but that gives us no results, the result is always empty. if i would remove the [arr] into arr, then the sql would get a variable amount of parameters, so i figured it should be [arr]. otherwise it would require us to add a dynamic amount of question marks (as many as there are id's in the array).
so can anyone see what i'm doing wrong?
aparently, there is no other solution, than to manually add a question mark for every item in your array.
this is actually in the specs on w3.org
var q = "";
for each (var i in labels)
q += (q == "" ? "" : ", ") + "?";
// later to be used as such:
t.executeSql('SELECT id FROM docs WHERE label IN (' + q + ')', labels, function (t, d) {
// do stuff with result...
});
more info here: http://www.w3.org/TR/webdatabase/#introduction (at the end of the introduction)
however, at the moment i created a helper function that creates such a string for me
might be better than the above, might not, i haven't done any performance testing.
this is what i use now
var createParamString = function(arr){
return _(arr).map(function(){ return "?"; }).join(',');
}
// when called like this:
createparamString([1,2,3,4,5]); // >> returns ?,?,?,?,?
this however makes use of the underscore.js library we have in our project.
Good answer. It was interesting to read an explanation in the official documentation.
I see this question was answered in 2012. I tried it in Google 37 exactly as it is recommened and this is what I got.
Data on input: (I outlined them with the black pencil)
Chrome complains:
So it accepts as many question signs as many input parameters are given. (Let us pay attention that although array is passed it's treated as one parameter)
Eventually I came up to this solution:
var activeItemIds = [1,2,3];
var q = "";
for (var i=0; i< activeItemIds.length; i++) {
q += '"' + activeItemIds[i] + '", ';
}
q= q.substring(0, q.length - 2);
var query = 'SELECT "id" FROM "products" WHERE "id" IN (' + q + ')';
_db.transaction(function (tx) {
tx.executeSql(query, [], function (tx, results1) {
console.log(results1);
debugger;
}, function (a, b) {
console.warn(a);
console.warn(b);
})
})