I am fairly new to this and please let me know if I am wrong in any point.
I am trying to convert WEI into Eth, without using the Web3 library.
const weiValue = 100000;
const ethValue = ethers.utils.formatEther(weiValue);<--- answer is correct at 0.0000000000001
My code requires me to change 40000000000000000 wei to eth.
and here is what I have:
const weiValue = 40000000000000000;
const tokenRateString = tokenRate.toString();
const ethValue = ethers.utils.formatEther();
I believe I need to convert the Wei into a string as it too large to be represented accurately as integers in JS
I am confused on what is the intermediate step here
To who ever comes here later.
Yes, a big number such like this : 40000000000000000 need to be a string.
What you need to do is this: 40000000000000000
const WeiToEth = (tokenRate)=> {
const weiValue = BigNumber.from("40000000000000000");
const ethValue = ethers.utils.formatEther(weiValue);
console.log(ethValue) }
It converts the number into a string
Here is the documentation : https://docs.ethers.io/v5/api/utils/bignumber/
Related
am trying to replace numbers in an array but am facing an issue which am not really able to correctly manage regarding how to correctly target the just one data I really have to change.
I'll make an example to have more accuracy on describing it.
Imagine my data array look like that:
["data", "phone numbers", "address"]
I can change numbers via following script but my first problem is that it makes no differences between the number it find in columns, for example "phone numbers" from "address" (at the moment am not using it, but should I include a ZIP code in the address it would be really be a problem)
Beside, my second and current problem with my script, is that obviosuly in the same "phone numnbers" a number may appear more times while I'd like to affect only the first block of the data - let's say to add/remove the country code (or even replace it with it's country vexillum) which I normally have like that "+1 0000000000" or "+54 0000000000"
So if a number is for example located in EU it really make this script useless: Spain is using "+34" while France "+33" and it wouldn't succeded in any case becouse it recognize only "+3" for both.
I've found some one else already facing this problems which seems to solved it wrapping the values inside a buondaries - for example like that "\b"constant"\b" - but either am wronging syntax either it does not really apply to my case. Others suggest to use forEach or Array.prototype.every which I failed to understand how to apply at this case.
Should you have other ideas about that am open to try it!
function phoneUPDATES(val)
{
var i= 0;
var array3 = val.value.split("\n");
for ( i = 0; i < array3.length; ++i) {
array3[i] = "+" + array3[i];
}
var arrayLINES = array3.join("\n");
const zero = "0";
const replaceZERO = "0";
const one = "1";
const replaceONE = "1";
const result0 = arrayLINES.replaceAll(zero, replaceZERO);
const result1 = result0.replaceAll(one, replaceONE);
const result2 = result1.replaceAll(two, replaceTWO);
const result3 = result2.replaceAll(thre, replaceTHREE);
const result4 = result3.replaceAll(four, replaceFOUR);
const result5 = result4.replaceAll(five, replaceFIVE);
const result6 = result5.replaceAll(six, replaceSIX);
const result7 = result6.replaceAll(seven, replaceSEVEN);
const result8 = result7.replaceAll(eight, replaceEIGHT);
const result9 = result8.replaceAll(nine, replaceNINE);
const result10 = result9.replaceAll(ten, replaceTEN);
const result11 = result10.replaceAll(eleven, replaceELEVEN);
Why not use a regex replace, you could do something like /(\+\d+ )/g which will find a + followed by one or more digits followed by a space, and then you can strip out the match:
const phoneNumbers = [, "+54 9876543210"]
console.log(phoneNumbers.map((num) => num.replaceAll(/(\+\d+ )/g, '')))
If you need to only target the second element in an array, i'd imagine your data looks like
const data = [["data", "+1 1234567890, +1 5555555555", "address"], ["data", "+11 111111111, +23 23232323", "address"]];
console.log(data.map((el) => {
el[1] = el[1].replaceAll(/(\+\d+ )/g, '');
return el;
}))
ok, this almost is cheating but I really didn't thought it before and, by the way does, not even actually solve the problems but jsut seems to work around it.
If I call the replacemente in decreasing order that problem just does not show up becouse condition of replacement involving higher numbers are matched before the smaller one.
but should some one suggest a complete "true code comply" solution is wellcome
I have an Angular project in which I have to implement datatrans payment. But I am not able to generate sign for payment.
I am following process given on this link (enter link description here) to generate sign.
But i am not able to achive it.
I am using angular library crypto-js to generate HMAC-SHA-256 signed string.
Here is my javascript code.
const merchantId = 'xxxxxxx';
const refNo = '1234567890';
const amount = 0;
const currency = 'CHF';
const theme = 'DT2015';
const paymentmethod = 'VIS';
const stringSs = merchantId+amount+currency+refNo;
const base = 16;
// My Hmac Key
const s = 'fa3d0ea1772cf21e53158283e4f123ebf1eb1ccfb15619e2fc91ee6860a2e5e48409e902b610ce5dc6f7f77fab8affb60d69b2a7aa9acf56723d868d36ab3f32';
// Step 1: Code to generate hex to byte of hmac key
const a = s.replace(/../g, '$&_').slice (0, -1).split ('_').map ((x) => parseInt (x, base));
// Step 3: Sign the string with HMAC-SHA-256 together with your HMAC key
const signedString = HmacSHA256(a, stringSs);
// Step 4: Translate the signature from byte to hex format
const signString = enc.Hex.stringify(signedString);
Can you help me into this to suggest what i am doing wrong or in what way it can be achieved.
You can do it with crypto (no need of extra libraries to install)
// Typescript
import * as crypto from 'crypto';
function signKey (clientKey: string, msg: string) {
const key = new Buffer(clientKey, 'hex');
return crypto.createHmac('sha256', key).update(msg).digest('hex');
}
// Javascript
const crypto = require('crypto')
function signKey (clientKey, msg) {
const key = new Buffer(clientKey, 'hex');
return crypto.createHmac('sha256', key).update(msg).digest('hex');
}
signKey(s, stringSs)
To answer the question for crypto-js (see https://github.com/brix/crypto-js) as requested, the following will do the trick:
// Javascript; example from datatrans documentation using a random key
stringSs ='3000017692850CHF91827364';
key='1ca12d7c0629194a9f9d0dbbc957709dd3aed385925b077e726813f0b452de6a38256abd1116138d21754cfb33964b6b1aaa375b74d3580fcda916898f553c92';
expectedSign='d7dee9ae1e542bc02bcb063a3dd3673871b2e43ccb4c230f26e8b85d14e25901';
signedString = CryptoJS.HmacSHA256(stringSs, CryptoJS.enc.Hex.parse(key));
resultSign = CryptoJS.enc.Hex.stringify(signedString);
// now resultSign == expectedSign is true :-)
Ninja Turtles approach was almost correct except of step 1, hex to byte. Use a builtin function of Crypto-JS instead and everything works as expected.
I have to read a JSON response which contains the value which is greater than MAX_SAFE_INTEGER without loss of precision. Like I had values
value1 = 232333433534534634534411
And I have to process that value and convert to
value2 = +232333433534534634534411.0000
without any loss of precision?
This can't be done with standard JSON.parse:
JSON.parse('{"prop": 232333433534534634534411}')
// {prop: 2.3233343353453462e+23}
If you have control over the API producing the JSON
You can use a string instead, then create a BigInt out of it (assuming legacy browser support isn't required).
const result = JSON.parse('{"prop": "232333433534534634534411"}')
const int = BigInt(result.prop)
// 232333433534534634534411n
If you need to perform decimal arithmetic on this result with a precision of 4 decimal places, you can multiply it by 10000n, for example:
const tenThousandths = int * 10000n // 2323334335345346345344110000n
const sum = tenThousandths + 55000n + 21n * 2n // 2323334335345346345344165042n
const fractionalPart = sum % 10000n // 5042n
const wholePart = sum / 10000n // 232333433534534634534416n (floor division)
const reStringified = `${wholePart}.${fractionalPart}` // "232333433534534634534416.5042"
const newJson = JSON.stringify({prop: reStringified})
// '{"prop":"232333433534534634534416.5042"}'
For legacy browser support, you could do similar with a library such as BigInteger.js.
If you don't control the API
In this case, you'll need a custom JSON parsing library, such as lossless JSON.
You could split by dot and treat the digits after the dot.
const convert = string => {
const values = string.split('.');
values[1] = (values[1] || '').padEnd(4, 0).slice(0, 4);
return values.join('.');
};
console.log(convert('232333433534534634534411'));
console.log(convert('232333433534534634534411.12345'));
I have used the below code to split my string.
splitter.map((item1) => {
let splitter1 = item1.split("=")[0].trimLeft();
let splitter2 = item1.split("=")[1].trimRight();
});
where item1 contains string as
Labor_Agreement=0349BP
Default_Hours=5/8
Probation_Period=>=12 Months
The issue I am facing is to restrict the amount of splits. Because the above code will fail in case of third string , i.e. Probation_Period=>=12 Months
I tried giving parameter to restrict the amount of split in split method above, but that is giving syntax error.
An easy to understand solution would consist of first finding the first = character, and slicing you array twice to get the right portion :
const strings = [
'Labor_Agreement=0349BP',
'Default_Hours=5/8',
'Probation_Period=>=12 Months',
];
strings.map(item => {
const chSplit = item.indexOf('=');
const splitter1 = item.slice(0, chSplit).trim();
const splitter2 = item.slice(chSplit + 1).trim();
console.log(splitter1, splitter2);
});
I am working on a project where I require to format incoming numbers in the following way:
###.###
However I noticed some results I didn't expect.
The following works in the sense that I don't get an error:
console.log(07);
// or in my case:
console.log(007);
Of course, it will not retain the '00' in the value itself, since that value is effectively 7.
The same goes for the following:
console.log(7.0);
// or in my case:
console.log(7.000);
JavaScript understands what I am doing, but in the end the actual value will be 7, which can be proven with the following:
const leadingValue = 007;
const trailingValue = 7.00;
console.log(leadingValue, trailingValue); // both are exactly 7
But what I find curious is the following: the moment I combine these two I get a syntax error:
// but not this:
console.log(007.000);
1) Can someone explain why this isn't working?
I'm trying to find a solution to store numbers/floats with the exact precision without using string.
2) Is there any way in JS/NodeJS or even TypeScript to do this without using strings?
What I currently want to do is to receive the input, scan for the format and store that as a separate property and then parse the incoming value since parseInt('007.000') does work. And when the user wants to get this value return it back to the user... in a string.. unfortunately.
1) 007.000 is a syntax error because 007 is an octal integer literal, to which you're then appending a floating point part. (Try console.log(010). This prints 8.)
2) Here's how you can achieve your formatting using Intl.NumberFormat...
var myformat = new Intl.NumberFormat('en-US', {
minimumIntegerDigits: 3,
minimumFractionDigits: 3
});
console.log(myformat.format(7)); // prints 007.000
Hi
You can use an aproach that uses string funtions .split .padStart and .padEnd
Search on MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
Here you have an example:
const x = 12.1;
function formatNumber( unformatedNumber) {
const desiredDecimalPad = 3;
const desiredNonDecimalPad = 3;
const unformatedNumberString = unformatedNumber.toString();
const unformatedNumberArr = unformatedNumberString.split('.');
const decimalStartPadded = unformatedNumberArr[0].padStart(desiredDecimalPad, '0');
const nonDecimalEndPadded = unformatedNumberArr[1].padEnd(desiredNonDecimalPad, '0');
const formatedNumberString = decimalStartPadded + '.' + nonDecimalEndPadded;
return formatedNumberString;
}
console.log(formatNumber(x))