mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-12-23 01:39:44 +01:00
Fix eth resolution
utils.formatBalance was returning rounded ether, was not useful for displaying account balances. Now returns four decimal points, and is easily configurable for more, with passing tests. Spoiler alert: Don't you dare divide bignumber wei. Bignumber does not have decimals. Keep it as wei, format it as ether.
This commit is contained in:
parent
5694a11672
commit
8527d051b0
@ -64,11 +64,16 @@ function weiToEth(bn) {
|
|||||||
return eth
|
return eth
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var decimalsToKeep = 4
|
||||||
function formatBalance(balance) {
|
function formatBalance(balance) {
|
||||||
if (!balance) return 'None'
|
if (!balance) return 'None'
|
||||||
var wei = numericBalance(balance)
|
var wei = numericBalance(balance)
|
||||||
var eth = weiToEth(wei)
|
var padded = wei.toString(10)
|
||||||
return eth.toString(10) + ' ETH'
|
var len = padded.length
|
||||||
|
var nonZeroIndex = padded.match(/[^0]/).index
|
||||||
|
var beforeDecimal = padded.substr(nonZeroIndex ? nonZeroIndex : 0, len - 18)
|
||||||
|
var afterDecimal = padded.substr(len - 18, decimalsToKeep)
|
||||||
|
return `${beforeDecimal}.${afterDecimal} ETH`
|
||||||
}
|
}
|
||||||
|
|
||||||
function dataSize(data) {
|
function dataSize(data) {
|
||||||
|
@ -63,9 +63,21 @@ describe('util', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('should return eth as string followed by ETH', function() {
|
it('should return eth as string followed by ETH', function() {
|
||||||
var input = new ethUtil.BN(ethInWei).toJSON()
|
var input = new ethUtil.BN(ethInWei, 10).toJSON()
|
||||||
var result = util.formatBalance(input)
|
var result = util.formatBalance(input)
|
||||||
assert.equal(result, '1 ETH')
|
assert.equal(result, '1.0000 ETH')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return eth as string followed by ETH', function() {
|
||||||
|
var input = new ethUtil.BN(ethInWei, 10).div(new ethUtil.BN('2', 10)).toJSON()
|
||||||
|
var result = util.formatBalance(input)
|
||||||
|
assert.equal(result, '.5000 ETH')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should display four decimal points', function() {
|
||||||
|
var input = "0x128dfa6a90b28000"
|
||||||
|
var result = util.formatBalance(input)
|
||||||
|
assert.equal(result, '1.3370 ETH')
|
||||||
})
|
})
|
||||||
|
|
||||||
})
|
})
|
||||||
|
Loading…
Reference in New Issue
Block a user