Reputation: 31
I'm working on an electron app HTML based and I'm stuck with a js code that separates numbers with a comma.
On my app, I get the number: 4,344.064 I want to remove and disable the "," as 4344.064
Here, this number is the number of tokens (erc20) held on an ethereum address and when I try to send a transaction with a web3 call (token from my address to another address), I'm only able to send up to 4 token so my app counts only the number before the ",".
I can send 1, 2, 3 or 4 tokens but when I try from 5 I can't so I'm sure that the problem come from the comma.
I've tried a lot of change on my js file but I'm unable to locate this function without removing the ".".
JS CODE :
function updateBalance() {
var address = myWallet.address;
$(".myaddress").html(address);
provider.getBalance(address).then(function(balance) {
var etherString = ethers.utils.formatEther(balance);
console.log("ETH Balance: " + etherString);
var n = parseFloat(etherString);
var ethValue = n.toLocaleString(
undefined, // use a string like 'en-US' to override browser
locale
{
minimumFractionDigits: 2
}
);
var messageEl = $('#ethbal');
var split = ethValue.split(".");
ethBalance = parseFloat(ethValue);
messageEl.html(split[0] + ".<small>" + split[1] + "</small>");
});
var callPromise = tokenContract.functions.balanceOf(address);
callPromise.then(function(result) {
var trueBal = result[0].toString(10);
var messageEl = $('#tokenbalance');
var n = trueBal * 0.00000001;
console.log("Token Balance: " + n);
var atyxValue = n.toLocaleString(
undefined, // use a string like 'en-US' to override browser
locale
{
minimumFractionDigits: 2
}
);
var split = atyxValue.split(".");
tokenBalance = parseFloat(atyxValue);
$(".neurealspend").html(atyxValue)
messageEl.html(split[0] + ".<small>" + split[1] + "</small>");
});
}
Thanks in advance for the help.
Upvotes: 2
Views: 1011
Reputation: 1004
This is "By Design". The parseFloat function will only consider the parts of the string up until in reaches a non +, -, number, exponent or decimal point. Once it sees the comma it stops looking and only considers the (in "4,344.064" only "4") portion.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat To fix this convert the commas to decimal points.
refer - Javascript parse float is ignoring the decimals after my comma
How ever there is a workaround, I would suggest to go like the below,
//source - https://stackoverflow.com/questions/7571553/javascript-parse-float-is-ignoring-the-decimals-after-my-comma/22453862
console.log(parseFloat(("43,434,344.064").replace(/[^\d\.\-]/g, "")))
Upvotes: 1