Skip to content

Commit

Permalink
Show the number with the correct rounding.
Browse files Browse the repository at this point in the history
  • Loading branch information
Pedro-vk committed Oct 23, 2019
1 parent 82a97ef commit 9a92c49
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
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

0 comments on commit 9a92c49

Please sign in to comment.