Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Wallet] Show the currency values with correct rounding. #1435

Merged
merged 1 commit into from
Oct 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/mobile/src/utils/formatting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import {

describe('utils->formatting', () => {
describe('getMoneyDisplayValue', () => {
const UNROUNDED_NUMBER = 5.239895
const ROUNDED_NUMBER_2_DECIMALS = '5.23'
const UNROUNDED_NUMBER = 5.239835
const ROUNDED_NUMBER_2_DECIMALS = '5.24'
const ROUNDED_NUMBER_3_DECIMALS = '5.239'

it('formats correctly for default case', () => {
Expand Down
29 changes: 25 additions & 4 deletions packages/mobile/src/utils/formatting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ const numeral = require('numeral')
export const getMoneyDisplayValue = (
value: BigNumber.Value,
currency: CURRENCY_ENUM = CURRENCY_ENUM.DOLLAR,
includeSymbol: boolean = false
includeSymbol: boolean = false,
roundingTolerance: number = 1
): string => {
const decimals = CURRENCIES[currency].displayDecimals
const symbol = CURRENCIES[currency].symbol
const formattedValue = numeral(roundDown(value, decimals).toNumber()).format(
const formattedValue = numeral(roundDown(value, decimals, roundingTolerance).toNumber()).format(
'0,0.' + '0'.repeat(decimals)
)
return includeSymbol ? symbol + formattedValue : formattedValue
Expand Down Expand Up @@ -57,11 +58,31 @@ export const divideByWei = (value: BigNumber.Value, decimals?: number) => {
return decimals ? bn.decimalPlaces(decimals) : bn
}

export function roundDown(value: BigNumber.Value, decimals: number = 2): BigNumber {
export function roundDown(
value: BigNumber.Value,
decimals: number = 2,
roundingTolerance: number = 0
): BigNumber {
if (roundingTolerance) {
value = new BigNumber(value).decimalPlaces(
decimals + roundingTolerance,
BigNumber.ROUND_HALF_DOWN
)
}
return new BigNumber(value).decimalPlaces(decimals, BigNumber.ROUND_DOWN)
}

export function roundUp(value: BigNumber.Value, decimals: number = 2): BigNumber {
export function roundUp(
value: BigNumber.Value,
decimals: number = 2,
roundingTolerance: number = 0
): BigNumber {
if (roundingTolerance) {
value = new BigNumber(value).decimalPlaces(
decimals + roundingTolerance,
BigNumber.ROUND_HALF_DOWN
)
}
return new BigNumber(value).decimalPlaces(decimals, BigNumber.ROUND_UP)
}

Expand Down