chore(#2179): update number formatters across frontend-monorepo (#2182)

* chore: update stagnet3 urls

* chore(#2179): remove normalized number formatter functions and update getNumberFormat

* fix(#2179): fix unit tests on all formatters

* fix(#2179): fix some cypress tests

* fix: fix  trading-accounts.cy.ts

* fix: update staking and wallet teardown tests

* chore: add e2e run-all command

* fix: wallet-eth test

* fix: fix tests in explorer and token

* fix: fix common.functions.js

* fix: fix common.functions.js in explorer

* fix(#2179): fix common.functions.js in explorer

* fix(#2179): fix common.functions.js in explorer

* fix(#2179): fix common.functions.js in explorer

Co-authored-by: Matthew Russell <mattrussell36@gmail.com>
This commit is contained in:
m.ray 2022-11-22 13:14:16 -05:00 committed by GitHub
parent 7c0bed2f14
commit 41646086e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 143 additions and 199 deletions

View File

@ -270,7 +270,10 @@ describe('Market trade', { tags: '@smoke' }, () => {
.find('dt') .find('dt')
.eq(3) .eq(3)
.should('have.text', 'Est. Fees (tDAI)'); .should('have.text', 'Est. Fees (tDAI)');
cy.get('#step-2-panel').find('dd').eq(3).should('have.text', '3 (3.03%)'); cy.get('#step-2-panel')
.find('dd')
.eq(3)
.should('have.text', '3.00 (3.03%)');
} }
}); });
@ -292,7 +295,10 @@ describe('Market trade', { tags: '@smoke' }, () => {
cy.get('#step-3-panel').find('dd').eq(2).should('have.text', '98.93006'); cy.get('#step-3-panel').find('dd').eq(2).should('have.text', '98.93006');
cy.get('#step-3-panel').find('dd').eq(3).should('have.text', '3 (3.03%)'); cy.get('#step-3-panel')
.find('dd')
.eq(3)
.should('have.text', '3.00 (3.03%)');
cy.get('#step-3-panel').find('dd').eq(4).should('have.text', ' - '); cy.get('#step-3-panel').find('dd').eq(4).should('have.text', ' - ');

View File

@ -23,7 +23,6 @@ import {
toDecimal, toDecimal,
removeDecimal, removeDecimal,
addDecimalsFormatNumber, addDecimalsFormatNumber,
addDecimalsNormalizeNumber,
addDecimal, addDecimal,
formatNumber, formatNumber,
} from '@vegaprotocol/react-helpers'; } from '@vegaprotocol/react-helpers';
@ -156,7 +155,7 @@ export const DealTicketSteps = ({ market }: DealTicketMarketProps) => {
.decimalPlaces(2) .decimalPlaces(2)
.toString(); .toString();
return `${addDecimalsNormalizeNumber( return `${addDecimalsFormatNumber(
estMargin.totalFees, estMargin.totalFees,
assetDecimals assetDecimals
)} (${formatNumber(addDecimal(percentage, assetDecimals), 2)}%)`; )} (${formatNumber(addDecimal(percentage, assetDecimals), 2)}%)`;

View File

@ -148,7 +148,7 @@ context('Network parameters page', { tags: '@smoke' }, function () {
const parameterName = network_parameter[0]; const parameterName = network_parameter[0];
const parameterValue = network_parameter[1]; const parameterValue = network_parameter[1];
if (this.networkParameterFormat.fiveDecimal.includes(parameterName)) { if (this.networkParameterFormat.fiveDecimal.includes(parameterName)) {
cy.convert_number_to_four_decimal(parameterValue) cy.convert_number_to_max_four_decimal(parameterValue)
.add_commas_to_number_if_large_enough() .add_commas_to_number_if_large_enough()
.then((parameterValueFormatted) => { .then((parameterValueFormatted) => {
cy.get(tableRows) cy.get(tableRows)
@ -179,7 +179,7 @@ context('Network parameters page', { tags: '@smoke' }, function () {
if ( if (
this.networkParameterFormat.eighteenDecimal.includes(parameterName) this.networkParameterFormat.eighteenDecimal.includes(parameterName)
) { ) {
cy.convert_number_to_eighteen_decimal(parameterValue) cy.convert_number_to_max_eighteen_decimal(parameterValue)
.add_commas_to_number_if_large_enough() .add_commas_to_number_if_large_enough()
.then((parameterValueFormatted) => { .then((parameterValueFormatted) => {
cy.get(tableRows) cy.get(tableRows)
@ -212,7 +212,7 @@ context('Network parameters page', { tags: '@smoke' }, function () {
const jsonFields = '.hljs'; const jsonFields = '.hljs';
const sideMenuBackground = '.absolute'; const sideMenuBackground = '.absolute';
// Engage dark mode if not allready set // Engage dark mode if not already set
cy.get(sideMenuBackground) cy.get(sideMenuBackground)
.should('have.css', 'background-color') .should('have.css', 'background-color')
.then((background_color) => { .then((background_color) => {

View File

@ -68,12 +68,19 @@ Cypress.Commands.add(
} }
); );
Cypress.Commands.add('convert_number_to_eighteen_decimal', (number) => { Cypress.Commands.add('convert_number_to_max_eighteen_decimal', (number) => {
// this will take a number like this : 700000000000000000000 // this will take a number like this : 700000000000000000001
// and convert it to a number like this: 700.000000000000000000 // and convert it to a number like this: 700.000000000000000001
return BigNumber((number / 1000000000000000000).toString()).toFixed(18); const value = BigNumber(number / 1000000000000000000).toString();
return parseFloat(value).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 18,
});
}); });
Cypress.Commands.add('convert_number_to_four_decimal', (number) => { Cypress.Commands.add('convert_number_to_max_four_decimal', (number) => {
return parseFloat(number).toFixed(4); return parseFloat(number).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 4,
});
}); });

View File

@ -644,7 +644,7 @@ context(
it('Unable to create a proposal - when no tokens are associated', function () { it('Unable to create a proposal - when no tokens are associated', function () {
cy.vega_wallet_teardown(); cy.vega_wallet_teardown();
cy.get(vegaWalletAssociatedBalance, txTimeout).contains( cy.get(vegaWalletAssociatedBalance, txTimeout).contains(
'0.000000000000000000', '0.00',
txTimeout txTimeout
); );
cy.go_to_make_new_proposal(governanceProposalType.RAW); cy.go_to_make_new_proposal(governanceProposalType.RAW);
@ -759,7 +759,7 @@ context(
cy.get(vegaWallet).within(() => { cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should( cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain', 'contain',
'0.999900000000000000' '0.9999'
); );
}); });
cy.navigate_to('governance'); cy.navigate_to('governance');
@ -804,7 +804,7 @@ context(
cy.get(connectToVegaWalletButton).should('not.exist'); cy.get(connectToVegaWalletButton).should('not.exist');
// 3001-VOTE-100 // 3001-VOTE-100
cy.get(vegaWalletAssociatedBalance, txTimeout).contains( cy.get(vegaWalletAssociatedBalance, txTimeout).contains(
'1.000000000000000000', '1.00',
txTimeout txTimeout
); );
cy.vote_for_proposal('against'); cy.vote_for_proposal('against');

View File

@ -554,7 +554,7 @@ context(
cy.get(vegaWallet).within(() => { cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should( cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain', 'contain',
'0.000000000000000000' '0.00'
); );
}); });
@ -608,7 +608,7 @@ context(
cy.get(vegaWallet).within(() => { cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should( cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain', 'contain',
'0.000000000000000000' '0.00'
); );
}); });
@ -656,7 +656,7 @@ context(
cy.get(vegaWallet).within(() => { cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should( cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain', 'contain',
'2.000000000000000000' '2.00'
); );
}); });
@ -819,7 +819,7 @@ context(
cy.get(vegaWallet).within(() => { cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should( cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain', 'contain',
'12.000000000000000000' '12.00'
); );
}); });

View File

@ -109,7 +109,7 @@ context(
cy.get(ethWalletAssociatedBalances, txTimeout) cy.get(ethWalletAssociatedBalances, txTimeout)
.contains(vegaWalletPublicKeyShort) .contains(vegaWalletPublicKeyShort)
.parent() .parent()
.should('contain', '1,001.000000000000000000', txTimeout); .should('contain', '1,001.00', txTimeout);
cy.get(ethWalletTotalAssociatedBalance, txTimeout) cy.get(ethWalletTotalAssociatedBalance, txTimeout)
.contains('1,001.00', txTimeout) .contains('1,001.00', txTimeout)
@ -118,7 +118,7 @@ context(
cy.get(vegaWallet).within(() => { cy.get(vegaWallet).within(() => {
cy.get(vegaWalletAssociatedBalance, txTimeout).should( cy.get(vegaWalletAssociatedBalance, txTimeout).should(
'contain', 'contain',
'1,001.000000000000000000' '1,001.00'
); );
}); });
}); });

View File

@ -79,7 +79,7 @@ context(
cy.getByTestId(withdraw).should('be.visible').click(); cy.getByTestId(withdraw).should('be.visible').click();
cy.getByTestId(selectAsset).select(usdtName); cy.getByTestId(selectAsset).select(usdtName);
cy.getByTestId(balanceAvailable, txTimeout).should('exist'); cy.getByTestId(balanceAvailable, txTimeout).should('exist');
cy.getByTestId(withdrawalThreshold).should('have.text', '100,000.00000T'); cy.getByTestId(withdrawalThreshold).should('have.text', '100,000.00T');
cy.getByTestId(delayTime).should('have.text', 'None'); cy.getByTestId(delayTime).should('have.text', 'None');
cy.getByTestId(amountInput).click().type('100'); cy.getByTestId(amountInput).click().type('100');
cy.getByTestId(submitWithdrawalButton).click(); cy.getByTestId(submitWithdrawalButton).click();
@ -94,7 +94,7 @@ context(
.should('have.attr', 'href') .should('have.attr', 'href')
.and('contain', '/txs/'); .and('contain', '/txs/');
cy.getByTestId(withdrawalAssetSymbol).should('have.text', usdcSymbol); cy.getByTestId(withdrawalAssetSymbol).should('have.text', usdcSymbol);
cy.getByTestId(withdrawalAmount).should('have.text', '100.00000'); cy.getByTestId(withdrawalAmount).should('have.text', '100.00');
cy.getByTestId(withdrawalRecipient) cy.getByTestId(withdrawalRecipient)
.should('have.text', truncatedWithdrawalEthAddress) .should('have.text', truncatedWithdrawalEthAddress)
.and('have.attr', 'href') .and('have.attr', 'href')
@ -118,7 +118,7 @@ context(
.parent() .parent()
.within(() => { .within(() => {
cy.get('[col-id="asset.symbol"]').should('have.text', usdcSymbol); cy.get('[col-id="asset.symbol"]').should('have.text', usdcSymbol);
cy.get('[col-id="amount"]').should('have.text', '100.00000'); cy.get('[col-id="amount"]').should('have.text', '100.00');
cy.get('[col-id="details.receiverAddress"]') cy.get('[col-id="details.receiverAddress"]')
.find('a') .find('a')
.should('have.attr', 'href') .should('have.attr', 'href')
@ -163,7 +163,7 @@ context(
.parent() .parent()
.within(() => { .within(() => {
cy.get('[col-id="asset.symbol"]').should('have.text', usdcSymbol); cy.get('[col-id="asset.symbol"]').should('have.text', usdcSymbol);
cy.get('[col-id="amount"]').should('have.text', '100.00000'); cy.get('[col-id="amount"]').should('have.text', '100.00');
cy.get('[col-id="details.receiverAddress"]') cy.get('[col-id="details.receiverAddress"]')
.find('a') .find('a')
.should('have.attr', 'href') .should('have.attr', 'href')

View File

@ -141,7 +141,7 @@ context(
cy.get(currencyValue) cy.get(currencyValue)
.should('be.visible') .should('be.visible')
.invoke('text') .invoke('text')
.should('match', /\d{0,3}(,\d{3})*\.\d{18}$/); .should('match', /\d{0,3}(,\d{3})*\.\d{2}$/);
}); });
}); });
@ -210,7 +210,7 @@ context(
cy.get(currencyValue) cy.get(currencyValue)
.should('be.visible') .should('be.visible')
.invoke('text') .invoke('text')
.should('match', /\d{0,3}(,\d{3})*\.\d{18}$/); .should('match', /\d{0,3}(,\d{3})*\.\d{2}$/);
}); });
}); });

View File

@ -197,18 +197,14 @@ context(
{ tags: '@smoke' }, { tags: '@smoke' },
function () { function () {
cy.get(walletContainer).within(() => { cy.get(walletContainer).within(() => {
cy.get(currencyValue) cy.get(currencyValue).should('be.visible').and('have.text', `0.00`);
.should('be.visible')
.and('have.text', `0.000000000000000000`);
}); });
} }
); );
it('should have Unstaked value visible', { tags: '@smoke' }, function () { it('should have Unstaked value visible', { tags: '@smoke' }, function () {
cy.get(walletContainer).within(() => { cy.get(walletContainer).within(() => {
cy.get(vegaUnstaked) cy.get(vegaUnstaked).should('be.visible').and('have.text', `0.00`);
.should('be.visible')
.and('have.text', `0.000000000000000000`);
}); });
}); });
@ -331,7 +327,7 @@ context(
.contains(currency.id) .contains(currency.id)
.parent() .parent()
.siblings() .siblings()
.within(() => cy.contains_exactly('10.00000').should('be.visible')); .within(() => cy.contains_exactly('10.00').should('be.visible'));
cy.get(vegaWalletCurrencyTitle) cy.get(vegaWalletCurrencyTitle)
.contains(currency.id) .contains(currency.id)
@ -351,7 +347,7 @@ context(
.contains(currency.id) .contains(currency.id)
.parent() .parent()
.siblings() .siblings()
.within(() => cy.contains_exactly('6.00000').should('be.visible')); .within(() => cy.contains_exactly('6.00').should('be.visible'));
cy.get(vegaWalletCurrencyTitle) cy.get(vegaWalletCurrencyTitle)
.contains(currency.id) .contains(currency.id)
@ -371,7 +367,7 @@ context(
.contains(currency.id) .contains(currency.id)
.parent() .parent()
.siblings() .siblings()
.within(() => cy.contains_exactly('8.00000').should('be.visible')); .within(() => cy.contains_exactly('8.00').should('be.visible'));
cy.get(vegaWalletCurrencyTitle) cy.get(vegaWalletCurrencyTitle)
.contains(currency.id) .contains(currency.id)
@ -391,7 +387,7 @@ context(
.contains(currency.id) .contains(currency.id)
.parent() .parent()
.siblings() .siblings()
.within(() => cy.contains_exactly('2.00000').should('be.visible')); .within(() => cy.contains_exactly('2.00').should('be.visible'));
cy.get(vegaWalletCurrencyTitle) cy.get(vegaWalletCurrencyTitle)
.contains(currency.id) .contains(currency.id)

View File

@ -208,7 +208,7 @@ Cypress.Commands.add(
if (parseFloat(unstakedBalance) != parseFloat(tokenAmount)) { if (parseFloat(unstakedBalance) != parseFloat(tokenAmount)) {
cy.vega_wallet_teardown(); cy.vega_wallet_teardown();
cy.get(vegaWalletAssociatedBalance, txTimeout).contains( cy.get(vegaWalletAssociatedBalance, txTimeout).contains(
'0.000000000000000000', '0.00',
txTimeout txTimeout
); );
cy.staking_page_associate_tokens(tokenAmount); cy.staking_page_associate_tokens(tokenAmount);

View File

@ -95,7 +95,7 @@ Cypress.Commands.add('vega_wallet_teardown', function () {
cy.get(vegaWalletAssociatedBalance) cy.get(vegaWalletAssociatedBalance)
.invoke('text') .invoke('text')
.then((balance) => { .then((balance) => {
if (balance != '0.000000000000000000') { if (balance != '0.00') {
cy.vega_wallet_teardown_vesting(this.vestingContract); cy.vega_wallet_teardown_vesting(this.vestingContract);
cy.vega_wallet_teardown_staking(this.stakingBridgeContract); cy.vega_wallet_teardown_staking(this.stakingBridgeContract);
} }
@ -105,7 +105,7 @@ Cypress.Commands.add('vega_wallet_teardown', function () {
cy.get(vegaWalletContainer).within(() => { cy.get(vegaWalletContainer).within(() => {
cy.get(vegaWalletAssociatedBalance, { timeout: transactionTimeout }).should( cy.get(vegaWalletAssociatedBalance, { timeout: transactionTimeout }).should(
'contain', 'contain',
'0.000000000000000000', '0.00',
{ timeout: transactionTimeout } { timeout: transactionTimeout }
); );
}); });

View File

@ -3,9 +3,9 @@ import { formatNumber } from './format-number';
describe('formatNumber and formatNumberPercentage', () => { describe('formatNumber and formatNumberPercentage', () => {
it.each([ it.each([
{ v: new BigNumber(123), d: 3, o: '123.000' }, { v: new BigNumber(123), d: 3, o: '123.00' },
{ v: new BigNumber(123.123), d: 3, o: '123.123' }, { v: new BigNumber(123.123), d: 3, o: '123.123' },
{ v: new BigNumber(123.123), d: 6, o: '123.123000' }, { v: new BigNumber(123.123), d: 6, o: '123.123' },
{ v: new BigNumber(123.123), d: 0, o: '123' }, { v: new BigNumber(123.123), d: 0, o: '123' },
{ v: new BigNumber(123), d: undefined, o: '123.00' }, // it default to 2 decimal places { v: new BigNumber(123), d: undefined, o: '123.00' }, // it default to 2 decimal places
{ v: new BigNumber(30000), d: undefined, o: '30,000.00' }, { v: new BigNumber(30000), d: undefined, o: '30,000.00' },

View File

@ -240,11 +240,11 @@ describe('Nodes list', () => {
expect( expect(
grid.querySelector('[role="gridcell"][col-id="stakeScore"]') grid.querySelector('[role="gridcell"][col-id="stakeScore"]')
).toHaveTextContent('0.23010'); ).toHaveTextContent('0.2301');
expect( expect(
grid.querySelector('[role="gridcell"][col-id="performanceScore"]') grid.querySelector('[role="gridcell"][col-id="performanceScore"]')
).toHaveTextContent('1.00000'); ).toHaveTextContent('1.00');
expect( expect(
grid.querySelector('[role="gridcell"][col-id="votingPower"]') grid.querySelector('[role="gridcell"][col-id="votingPower"]')

View File

@ -28,6 +28,6 @@ describe('accounts', { tags: '@smoke' }, () => {
cy.getByTestId('tab-accounts') cy.getByTestId('tab-accounts')
.get(tradingAccountRowId) .get(tradingAccountRowId)
.find('[col-id="deposited"]') .find('[col-id="deposited"]')
.should('have.text', '1,000'); .should('have.text', '1,000.00');
}); });
}); });

View File

@ -51,7 +51,7 @@ describe('withdraw', { tags: '@smoke' }, () => {
); );
}); });
it('max amount', () => { it('max amount', () => {
selectAsset(asset2Name); // Will be above maximum because the vega wallet doesnt have any collateral selectAsset(asset2Name); // Will be above maximum because the vega wallet doesn't have any collateral
cy.get(amountField).clear().type('1001', { delay: 100 }); cy.get(amountField).clear().type('1001', { delay: 100 });
cy.getByTestId(submitWithdrawBtn).click(); cy.getByTestId(submitWithdrawBtn).click();
cy.get('[data-testid="input-error-text"]').should( cy.get('[data-testid="input-error-text"]').should(
@ -81,17 +81,14 @@ describe('withdraw', { tags: '@smoke' }, () => {
'contain.text', 'contain.text',
'Balance available' 'Balance available'
); );
cy.getByTestId('BALANCE_AVAILABLE_value').should( cy.getByTestId('BALANCE_AVAILABLE_value').should('have.text', '1,000.00');
'have.text',
'1,000.00000'
);
cy.getByTestId('WITHDRAWAL_THRESHOLD_label').should( cy.getByTestId('WITHDRAWAL_THRESHOLD_label').should(
'contain.text', 'contain.text',
'Delayed withdrawal threshold' 'Delayed withdrawal threshold'
); );
cy.getByTestId('WITHDRAWAL_THRESHOLD_value').should( cy.getByTestId('WITHDRAWAL_THRESHOLD_value').should(
'contain.text', 'contain.text',
'100.00000' '100.00'
); );
cy.getByTestId('DELAY_TIME_label').should('contain.text', 'Delay time'); cy.getByTestId('DELAY_TIME_label').should('contain.text', 'Delay time');
cy.getByTestId('DELAY_TIME_value').should('have.text', 'None'); cy.getByTestId('DELAY_TIME_value').should('have.text', 'None');

View File

@ -6,7 +6,7 @@ import {
} from '@vegaprotocol/liquidity'; } from '@vegaprotocol/liquidity';
import { tooltipMapping } from '@vegaprotocol/market-info'; import { tooltipMapping } from '@vegaprotocol/market-info';
import { import {
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
NetworkParams, NetworkParams,
t, t,
useDataProvider, useDataProvider,
@ -151,7 +151,7 @@ export const Liquidity = () => {
> >
<div> <div>
{targetStake {targetStake
? `${addDecimalsNormalizeNumber( ? `${addDecimalsFormatNumber(
targetStake, targetStake,
assetDecimalPlaces ?? 0 assetDecimalPlaces ?? 0
)} ${symbol}` )} ${symbol}`
@ -164,7 +164,7 @@ export const Liquidity = () => {
> >
<div> <div>
{suppliedStake {suppliedStake
? `${addDecimalsNormalizeNumber( ? `${addDecimalsFormatNumber(
suppliedStake, suppliedStake,
assetDecimalPlaces ?? 0 assetDecimalPlaces ?? 0
)} ${symbol}` )} ${symbol}`

View File

@ -7,7 +7,7 @@ import {
calcCandleVolume, calcCandleVolume,
} from '@vegaprotocol/market-list'; } from '@vegaprotocol/market-list';
import { import {
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
PriceCell, PriceCell,
signedNumberCssClass, signedNumberCssClass,
t, t,
@ -251,7 +251,7 @@ export const columns = (
value: market.data?.markPrice ? ( value: market.data?.markPrice ? (
<PriceCell <PriceCell
value={Number(market.data?.markPrice)} value={Number(market.data?.markPrice)}
valueFormatted={addDecimalsNormalizeNumber( valueFormatted={addDecimalsFormatNumber(
market.data?.markPrice.toString(), market.data?.markPrice.toString(),
market.decimalPlaces, market.decimalPlaces,
2 2
@ -315,7 +315,7 @@ export const columns = (
value: candleHigh ? ( value: candleHigh ? (
<PriceCell <PriceCell
value={Number(candleHigh)} value={Number(candleHigh)}
valueFormatted={addDecimalsNormalizeNumber( valueFormatted={addDecimalsFormatNumber(
candleHigh.toString(), candleHigh.toString(),
market.decimalPlaces, market.decimalPlaces,
2 2
@ -332,7 +332,7 @@ export const columns = (
value: candleLow ? ( value: candleLow ? (
<PriceCell <PriceCell
value={Number(candleLow)} value={Number(candleLow)}
valueFormatted={addDecimalsNormalizeNumber( valueFormatted={addDecimalsFormatNumber(
candleLow.toString(), candleLow.toString(),
market.decimalPlaces, market.decimalPlaces,
2 2
@ -347,7 +347,7 @@ export const columns = (
{ {
kind: ColumnKind.Volume, kind: ColumnKind.Volume,
value: candleVolume value: candleVolume
? addDecimalsNormalizeNumber( ? addDecimalsFormatNumber(
candleVolume.toString(), candleVolume.toString(),
market.positionDecimalPlaces, market.positionDecimalPlaces,
2 2
@ -432,7 +432,7 @@ export const columnsPositionMarkets = (
value: market.data?.markPrice ? ( value: market.data?.markPrice ? (
<PriceCell <PriceCell
value={Number(market.data.markPrice)} value={Number(market.data.markPrice)}
valueFormatted={addDecimalsNormalizeNumber( valueFormatted={addDecimalsFormatNumber(
market.data.markPrice.toString(), market.data.markPrice.toString(),
market.decimalPlaces, market.decimalPlaces,
2 2
@ -496,7 +496,7 @@ export const columnsPositionMarkets = (
value: candleHigh ? ( value: candleHigh ? (
<PriceCell <PriceCell
value={Number(candleHigh)} value={Number(candleHigh)}
valueFormatted={addDecimalsNormalizeNumber( valueFormatted={addDecimalsFormatNumber(
candleHigh.toString(), candleHigh.toString(),
market.decimalPlaces, market.decimalPlaces,
2 2
@ -513,7 +513,7 @@ export const columnsPositionMarkets = (
value: candleLow ? ( value: candleLow ? (
<PriceCell <PriceCell
value={Number(candleLow)} value={Number(candleLow)}
valueFormatted={addDecimalsNormalizeNumber( valueFormatted={addDecimalsFormatNumber(
candleLow.toString(), candleLow.toString(),
market.decimalPlaces, market.decimalPlaces,
2 2
@ -528,7 +528,7 @@ export const columnsPositionMarkets = (
{ {
kind: ColumnKind.Volume, kind: ColumnKind.Volume,
value: candleVolume value: candleVolume
? addDecimalsNormalizeNumber( ? addDecimalsFormatNumber(
candleVolume.toString(), candleVolume.toString(),
market.positionDecimalPlaces, market.positionDecimalPlaces,
2 2
@ -556,10 +556,7 @@ export const columnsPositionMarkets = (
value: ( value: (
<p className={signedNumberCssClass(openVolume || '')}> <p className={signedNumberCssClass(openVolume || '')}>
{openVolume && {openVolume &&
addDecimalsNormalizeNumber( addDecimalsFormatNumber(openVolume, market.positionDecimalPlaces)}
openVolume,
market.positionDecimalPlaces
)}
</p> </p>
), ),
className: `${cellClassNames} hidden xxl:table-cell font-mono`, className: `${cellClassNames} hidden xxl:table-cell font-mono`,

View File

@ -55,8 +55,8 @@ describe('AccountsTable', () => {
const cells = await screen.findAllByRole('gridcell'); const cells = await screen.findAllByRole('gridcell');
const expectedValues = [ const expectedValues = [
'tBTC', 'tBTC',
'1,256', '1,256.00',
'1,2561,256', '1,256.001,256.00',
'Breakdown', 'Breakdown',
'Deposit', 'Deposit',
]; ];

View File

@ -2,7 +2,7 @@ import { forwardRef, useState } from 'react';
import type { ValueFormatterParams } from 'ag-grid-community'; import type { ValueFormatterParams } from 'ag-grid-community';
import type { Asset } from '@vegaprotocol/assets'; import type { Asset } from '@vegaprotocol/assets';
import { import {
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
isNumeric, isNumeric,
t, t,
} from '@vegaprotocol/react-helpers'; } from '@vegaprotocol/react-helpers';
@ -38,8 +38,8 @@ export const progressBarValueFormatter = ({
const max = BigInt(data.deposited); const max = BigInt(data.deposited);
const range = max > min ? max : min; const range = max > min ? max : min;
return { return {
low: addDecimalsNormalizeNumber(min.toString(), data.asset.decimals, 4), low: addDecimalsFormatNumber(min.toString(), data.asset.decimals, 4),
high: addDecimalsNormalizeNumber(mid.toString(), data.asset.decimals, 4), high: addDecimalsFormatNumber(mid.toString(), data.asset.decimals, 4),
value: range ? Number((min * BigInt(100)) / range) : 0, value: range ? Number((min * BigInt(100)) / range) : 0,
intent: Intent.Warning, intent: Intent.Warning,
}; };
@ -125,7 +125,7 @@ export const AccountTable = forwardRef<AgGridReact, AccountTableProps>(
data && data &&
data.asset && data.asset &&
isNumeric(value) && isNumeric(value) &&
addDecimalsNormalizeNumber(value, data.asset.decimals) addDecimalsFormatNumber(value, data.asset.decimals)
} }
maxWidth={300} maxWidth={300}
/> />

View File

@ -51,9 +51,9 @@ describe('BreakdownTable', () => {
const expectedValues = [ const expectedValues = [
'Margin', 'Margin',
'BTCUSD Monthly (30 Jun 2022)', 'BTCUSD Monthly (30 Jun 2022)',
'1,2561,256', '1,256.001,256.00',
'1,256', '1,256.00',
'1,256', '1,256.00',
]; ];
cells.forEach((cell, i) => { cells.forEach((cell, i) => {
expect(cell).toHaveTextContent(expectedValues[i]); expect(cell).toHaveTextContent(expectedValues[i]);

View File

@ -1,4 +1,4 @@
import { addDecimalsNormalizeNumber, t } from '@vegaprotocol/react-helpers'; import { addDecimalsFormatNumber, t } from '@vegaprotocol/react-helpers';
import type { Schema } from '@vegaprotocol/types'; import type { Schema } from '@vegaprotocol/types';
import type { KeyValueTableRowProps } from '@vegaprotocol/ui-toolkit'; import type { KeyValueTableRowProps } from '@vegaprotocol/ui-toolkit';
import { import {
@ -43,7 +43,7 @@ type Mapping = { [key in string]: { value: string; tooltip: string } };
const num = (asset: Asset, n: string | undefined | null) => { const num = (asset: Asset, n: string | undefined | null) => {
if (typeof n === 'undefined' || n == null) return ''; if (typeof n === 'undefined' || n == null) return '';
return addDecimalsNormalizeNumber(n, asset.decimals); return addDecimalsFormatNumber(n, asset.decimals);
}; };
export const rows: Rows = [ export const rows: Rows = [

View File

@ -1,4 +1,4 @@
import { normalizeFormatNumber, t } from '@vegaprotocol/react-helpers'; import { formatNumber, t } from '@vegaprotocol/react-helpers';
import { ButtonLink } from '@vegaprotocol/ui-toolkit'; import { ButtonLink } from '@vegaprotocol/ui-toolkit';
import { DepositDialog, useDepositDialog } from '@vegaprotocol/deposits'; import { DepositDialog, useDepositDialog } from '@vegaprotocol/deposits';
@ -30,12 +30,11 @@ export const MarginWarning = ({ margin, balance, asset }: Props) => {
</ButtonLink> </ButtonLink>
</p> </p>
<p> <p>
{`${normalizeFormatNumber(margin, asset.decimals)} ${ {`${formatNumber(margin, asset.decimals)} ${asset.symbol} ${t(
asset.symbol 'currently required'
} ${t('currently required')}, ${normalizeFormatNumber( )}, ${formatNumber(balance, asset.decimals)} ${asset.symbol} ${t(
balance, 'available'
asset.decimals )}`}
)} ${asset.symbol} ${t('available')}`}
</p> </p>
</div> </div>
<DepositDialog /> <DepositDialog />

View File

@ -1,7 +1,7 @@
import { import {
t, t,
getDateTimeFormat, getDateTimeFormat,
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
} from '@vegaprotocol/react-helpers'; } from '@vegaprotocol/react-helpers';
import { Schema } from '@vegaprotocol/types'; import { Schema } from '@vegaprotocol/types';
import { Link as UILink } from '@vegaprotocol/ui-toolkit'; import { Link as UILink } from '@vegaprotocol/ui-toolkit';
@ -21,7 +21,7 @@ export const compileGridData = (
market.data?.trigger === Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY; market.data?.trigger === Schema.AuctionTrigger.AUCTION_TRIGGER_LIQUIDITY;
const formatStake = (value: string) => { const formatStake = (value: string) => {
const formattedValue = addDecimalsNormalizeNumber( const formattedValue = addDecimalsFormatNumber(
value, value,
market.tradableInstrument.instrument.product.settlementAsset.decimals market.tradableInstrument.instrument.product.settlementAsset.decimals
); );
@ -77,7 +77,7 @@ export const compileGridData = (
value: value:
market.data.indicativePrice && market.data.indicativePrice !== '0' market.data.indicativePrice && market.data.indicativePrice !== '0'
? `~ ? `~
${addDecimalsNormalizeNumber( ${addDecimalsFormatNumber(
market.data.indicativePrice, market.data.indicativePrice,
market.decimalPlaces market.decimalPlaces
)}` )}`
@ -91,7 +91,7 @@ export const compileGridData = (
value: value:
market.data.indicativeVolume && market.data.indicativeVolume !== '0' market.data.indicativeVolume && market.data.indicativeVolume !== '0'
? '~' + ? '~' +
addDecimalsNormalizeNumber( addDecimalsFormatNumber(
market.data.indicativeVolume, market.data.indicativeVolume,
market.positionDecimalPlaces market.positionDecimalPlaces
) )

View File

@ -1,7 +1,7 @@
import { FeesBreakdown } from '@vegaprotocol/market-info'; import { FeesBreakdown } from '@vegaprotocol/market-info';
import { import {
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
normalizeFormatNumber, formatNumber,
t, t,
} from '@vegaprotocol/react-helpers'; } from '@vegaprotocol/react-helpers';
import { Schema } from '@vegaprotocol/types'; import { Schema } from '@vegaprotocol/types';
@ -116,14 +116,14 @@ export const getFeeDetailsValues = ({
value: string | number | null | undefined value: string | number | null | undefined
): string => { ): string => {
return value && !isNaN(Number(value)) return value && !isNaN(Number(value))
? normalizeFormatNumber(value, market.decimalPlaces) ? formatNumber(value, market.decimalPlaces)
: '-'; : '-';
}; };
const formatValueWithAssetDp = ( const formatValueWithAssetDp = (
value: string | number | null | undefined value: string | number | null | undefined
): string => { ): string => {
return value && !isNaN(Number(value)) return value && !isNaN(Number(value))
? addDecimalsNormalizeNumber(value, assetDecimals) ? addDecimalsFormatNumber(value, assetDecimals)
: '-'; : '-';
}; };
return [ return [

View File

@ -82,7 +82,7 @@ describe('useOrderCloseOut', () => {
), ),
} }
); );
expect(result.current).toEqual('1.00000'); expect(result.current).toEqual('1.00');
}); });
it('should return proper empty value', () => { it('should return proper empty value', () => {
@ -101,6 +101,6 @@ describe('useOrderCloseOut', () => {
), ),
} }
); );
expect(result.current).toEqual('0.00000'); expect(result.current).toEqual('0.00');
}); });
}); });

View File

@ -89,7 +89,7 @@ describe('FillsTable', () => {
const cells = screen.getAllByRole('gridcell'); const cells = screen.getAllByRole('gridcell');
const expectedValues = [ const expectedValues = [
buyerFill.market?.tradableInstrument.instrument.name || '', buyerFill.market?.tradableInstrument.instrument.name || '',
'+3.00000', '+3.00',
'1.00 BTC', '1.00 BTC',
'3.00 BTC', '3.00 BTC',
'Maker', 'Maker',
@ -126,7 +126,7 @@ describe('FillsTable', () => {
const cells = screen.getAllByRole('gridcell'); const cells = screen.getAllByRole('gridcell');
const expectedValues = [ const expectedValues = [
buyerFill.market?.tradableInstrument.instrument.name || '', buyerFill.market?.tradableInstrument.instrument.name || '',
'-3.00000', '-3.00',
'1.00 BTC', '1.00 BTC',
'3.00 BTC', '3.00 BTC',
'Taker', 'Taker',

View File

@ -1,6 +1,6 @@
import { forwardRef } from 'react'; import { forwardRef } from 'react';
import { import {
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
formatNumberPercentage, formatNumberPercentage,
getDateTimeFormat, getDateTimeFormat,
t, t,
@ -41,18 +41,14 @@ export const LiquidityTable = forwardRef<AgGridReact, LiquidityTableProps>(
({ data, symbol = '', assetDecimalPlaces, stakeToCcySiskas }, ref) => { ({ data, symbol = '', assetDecimalPlaces, stakeToCcySiskas }, ref) => {
const assetDecimalsFormatter = ({ value }: ValueFormatterParams) => { const assetDecimalsFormatter = ({ value }: ValueFormatterParams) => {
if (!value) return '-'; if (!value) return '-';
return `${addDecimalsNormalizeNumber(value, assetDecimalPlaces ?? 0, 5)}`; return `${addDecimalsFormatNumber(value, assetDecimalPlaces ?? 0, 5)}`;
}; };
const stakeToCcySiskasFormatter = ({ value }: ValueFormatterParams) => { const stakeToCcySiskasFormatter = ({ value }: ValueFormatterParams) => {
if (!value) return '-'; if (!value) return '-';
const newValue = new BigNumber(value) const newValue = new BigNumber(value)
.times(stakeToCcySiskas ?? 1) .times(stakeToCcySiskas ?? 1)
.toString(); .toString();
return `${addDecimalsNormalizeNumber( return `${addDecimalsFormatNumber(newValue, assetDecimalPlaces ?? 0, 5)}`;
newValue,
assetDecimalPlaces ?? 0,
5
)}`;
}; };
if (!data) return null; if (!data) return null;

View File

@ -1,6 +1,6 @@
import { totalFeesPercentage } from '@vegaprotocol/market-list'; import { totalFeesPercentage } from '@vegaprotocol/market-list';
import { import {
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
formatNumberPercentage, formatNumberPercentage,
t, t,
} from '@vegaprotocol/react-helpers'; } from '@vegaprotocol/react-helpers';
@ -70,7 +70,7 @@ export const FeesBreakdown = ({
.toString(); .toString();
const formatValue = (value: string | number | null | undefined): string => { const formatValue = (value: string | number | null | undefined): string => {
return value && !isNaN(Number(value)) return value && !isNaN(Number(value))
? addDecimalsNormalizeNumber(value, decimals) ? addDecimalsFormatNumber(value, decimals)
: '-'; : '-';
}; };
return ( return (

View File

@ -1,5 +1,5 @@
import { import {
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
formatNumber, formatNumber,
formatNumberPercentage, formatNumberPercentage,
t, t,
@ -40,10 +40,7 @@ const Row = ({
return value; return value;
} }
if (decimalPlaces) { if (decimalPlaces) {
return `${addDecimalsNormalizeNumber( return `${addDecimalsFormatNumber(value, decimalPlaces)} ${assetSymbol}`;
value,
decimalPlaces
)} ${assetSymbol}`;
} }
if (asPercentage) { if (asPercentage) {
return formatNumberPercentage(new BigNumber(value).times(100)); return formatNumberPercentage(new BigNumber(value).times(100));

View File

@ -4,7 +4,7 @@ import {
Size, Size,
getDateTimeFormat, getDateTimeFormat,
addDecimal, addDecimal,
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
} from '@vegaprotocol/react-helpers'; } from '@vegaprotocol/react-helpers';
import { Schema } from '@vegaprotocol/types'; import { Schema } from '@vegaprotocol/types';
import { import {
@ -68,10 +68,7 @@ export const OrderEditDialog = ({
<div className="md:col-span-1"> <div className="md:col-span-1">
<p className={headerClassName}>{t(`Price`)}</p> <p className={headerClassName}>{t(`Price`)}</p>
<p> <p>
{addDecimalsNormalizeNumber( {addDecimalsFormatNumber(order.price, order.market.decimalPlaces)}
order.price,
order.market.decimalPlaces
)}
</p> </p>
</div> </div>
)} )}

View File

@ -92,7 +92,7 @@ it('add color and sign to amount, displays positive notional value', async () =>
expect(cells[2].classList.contains('text-vega-green-dark')).toBeTruthy(); expect(cells[2].classList.contains('text-vega-green-dark')).toBeTruthy();
expect(cells[2].classList.contains('text-vega-red-dark')).toBeFalsy(); expect(cells[2].classList.contains('text-vega-red-dark')).toBeFalsy();
expect(cells[2].textContent).toEqual('+100'); expect(cells[2].textContent).toEqual('+100');
expect(cells[1].textContent).toEqual('1,230'); expect(cells[1].textContent).toEqual('1,230.0');
await act(async () => { await act(async () => {
result.rerender( result.rerender(
<PositionsTable rowData={[{ ...singleRow, openVolume: '-100' }]} /> <PositionsTable rowData={[{ ...singleRow, openVolume: '-100' }]} />
@ -102,7 +102,7 @@ it('add color and sign to amount, displays positive notional value', async () =>
expect(cells[2].classList.contains('text-vega-green-dark')).toBeFalsy(); expect(cells[2].classList.contains('text-vega-green-dark')).toBeFalsy();
expect(cells[2].classList.contains('text-vega-red-dark')).toBeTruthy(); expect(cells[2].classList.contains('text-vega-red-dark')).toBeTruthy();
expect(cells[2].textContent?.startsWith('-100')).toBeTruthy(); expect(cells[2].textContent?.startsWith('-100')).toBeTruthy();
expect(cells[1].textContent).toEqual('1,230'); expect(cells[1].textContent).toEqual('1,230.0');
}); });
it('displays mark price', async () => { it('displays mark price', async () => {
@ -162,7 +162,7 @@ it('displays allocated margin', async () => {
}); });
const cells = screen.getAllByRole('gridcell'); const cells = screen.getAllByRole('gridcell');
const cell = cells[8]; const cell = cells[8];
expect(cell.textContent).toEqual('123,456'); expect(cell.textContent).toEqual('123,456.00');
}); });
it('displays realised and unrealised PNL', async () => { it('displays realised and unrealised PNL', async () => {

View File

@ -10,7 +10,7 @@ import type {
import { ProgressBarCell } from '@vegaprotocol/ui-toolkit'; import { ProgressBarCell } from '@vegaprotocol/ui-toolkit';
import { import {
PriceFlashCell, PriceFlashCell,
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
volumePrefix, volumePrefix,
t, t,
toBigNum, toBigNum,
@ -68,11 +68,11 @@ export const AmountCell = ({ valueFormatted }: AmountCellProps) => {
className={classNames('text-right', signedNumberCssClass(openVolume))} className={classNames('text-right', signedNumberCssClass(openVolume))}
> >
{volumePrefix( {volumePrefix(
addDecimalsNormalizeNumber(openVolume, positionDecimalPlaces) addDecimalsFormatNumber(openVolume, positionDecimalPlaces)
)} )}
</div> </div>
<div className="text-right"> <div className="text-right">
{addDecimalsNormalizeNumber(notional, marketDecimalPlaces)} {addDecimalsFormatNumber(notional, marketDecimalPlaces)}
</div> </div>
</div> </div>
) : null; ) : null;
@ -155,7 +155,7 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
}: VegaValueFormatterParams<Position, 'notional'>) => { }: VegaValueFormatterParams<Position, 'notional'>) => {
return !data return !data
? undefined ? undefined
: addDecimalsNormalizeNumber( : addDecimalsFormatNumber(
data.notional, data.notional,
data.marketDecimalPlaces data.marketDecimalPlaces
); );
@ -183,7 +183,7 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
return data?.openVolume === undefined return data?.openVolume === undefined
? undefined ? undefined
: volumePrefix( : volumePrefix(
addDecimalsNormalizeNumber( addDecimalsFormatNumber(
data.openVolume, data.openVolume,
data.positionDecimalPlaces data.positionDecimalPlaces
) )
@ -222,7 +222,7 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
) { ) {
return '-'; return '-';
} }
return addDecimalsNormalizeNumber( return addDecimalsFormatNumber(
data.markPrice, data.markPrice,
data.marketDecimalPlaces data.marketDecimalPlaces
); );
@ -258,7 +258,7 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
if (!data) { if (!data) {
return undefined; return undefined;
} }
return addDecimalsNormalizeNumber( return addDecimalsFormatNumber(
data.averageEntryPrice, data.averageEntryPrice,
data.marketDecimalPlaces data.marketDecimalPlaces
); );
@ -292,7 +292,7 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
if (!data) { if (!data) {
return undefined; return undefined;
} }
return addDecimalsNormalizeNumber( return addDecimalsFormatNumber(
data.liquidationPrice, data.liquidationPrice,
data.marketDecimalPlaces data.marketDecimalPlaces
); );
@ -340,7 +340,7 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
if (!data) { if (!data) {
return undefined; return undefined;
} }
return addDecimalsNormalizeNumber( return addDecimalsFormatNumber(
data.marginAccountBalance, data.marginAccountBalance,
data.decimals data.decimals
); );
@ -364,7 +364,7 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
}: VegaValueFormatterParams<Position, 'realisedPNL'>) => { }: VegaValueFormatterParams<Position, 'realisedPNL'>) => {
return !data return !data
? undefined ? undefined
: addDecimalsNormalizeNumber(data.realisedPNL, data.decimals); : addDecimalsFormatNumber(data.realisedPNL, data.decimals);
}} }}
cellRenderer="PriceFlashCell" cellRenderer="PriceFlashCell"
headerTooltip={t( headerTooltip={t(
@ -389,7 +389,7 @@ export const PositionsTable = forwardRef<AgGridReact, Props>(
}: VegaValueFormatterParams<Position, 'unrealisedPNL'>) => }: VegaValueFormatterParams<Position, 'unrealisedPNL'>) =>
!data !data
? undefined ? undefined
: addDecimalsNormalizeNumber(data.unrealisedPNL, data.decimals) : addDecimalsFormatNumber(data.unrealisedPNL, data.decimals)
} }
cellRenderer="PriceFlashCell" cellRenderer="PriceFlashCell"
headerTooltip={t( headerTooltip={t(

View File

@ -1,50 +1,33 @@
import BigNumber from 'bignumber.js'; import BigNumber from 'bignumber.js';
import { import {
addDecimalsNormalizeNumber, addDecimalsFormatNumber,
compactNumber, compactNumber,
formatNumber, formatNumber,
formatNumberPercentage, formatNumberPercentage,
isNumeric, isNumeric,
normalizeFormatNumber,
toNumberParts, toNumberParts,
} from './number'; } from './number';
describe('number react-helpers', () => { describe('number react-helpers', () => {
it.each([ it.each([
{ v: new BigNumber(123000), d: 5, o: '1.23' }, { v: new BigNumber(123000), d: 5, o: '1.23' },
{ v: new BigNumber(123000), d: 3, o: '123' }, { v: new BigNumber(123000), d: 3, o: '123.00' },
{ v: new BigNumber(123000), d: 1, o: '12,300' }, { v: new BigNumber(123000), d: 1, o: '12,300.0' },
{ v: new BigNumber(123001), d: 2, o: '1,230.01' }, { v: new BigNumber(123001), d: 2, o: '1,230.01' },
{ v: new BigNumber(123001000), d: 2, o: '1,230,010' }, { v: new BigNumber(123001000), d: 2, o: '1,230,010.00' },
])( ])(
'formats with addDecimalsNormalizeNumber given number correctly', 'formats with addDecimalsFormatNumber given number correctly',
({ v, d, o }) => { ({ v, d, o }) => {
expect(addDecimalsNormalizeNumber(v.toString(), d)).toStrictEqual(o); expect(addDecimalsFormatNumber(v.toString(), d)).toStrictEqual(o);
} }
); );
it.each([ it.each([
{ v: new BigNumber(123.0), d: 3, o: '123' }, { v: new BigNumber(123), d: 3, o: '123.00' },
{ v: new BigNumber(123.123), d: 3, o: '123.123' }, { v: new BigNumber(123.123), d: 3, o: '123.123' },
{ v: new BigNumber(123.6666), d: 3, o: '123.667' }, { v: new BigNumber(123.6666), d: 3, o: '123.667' },
{ v: new BigNumber(123.003), d: 6, o: '123.003' }, { v: new BigNumber(123.123), d: 6, o: '123.123' },
{ v: new BigNumber(123.003), d: 0, o: '123' },
{ v: new BigNumber(123), d: undefined, o: '123' },
{ v: new BigNumber(30000), d: undefined, o: '30,000' },
{ v: new BigNumber(3.000001), d: undefined, o: '3' },
])(
`formats with normalizeFormatNumber given number correctly`,
({ v, d, o }) => {
expect(normalizeFormatNumber(v, d)).toStrictEqual(o);
}
);
it.each([
{ v: new BigNumber(123), d: 3, o: '123.000' },
{ v: new BigNumber(123.123), d: 3, o: '123.123' },
{ v: new BigNumber(123.6666), d: 3, o: '123.667' },
{ v: new BigNumber(123.123), d: 6, o: '123.123000' },
{ v: new BigNumber(123.123), d: 0, o: '123' }, { v: new BigNumber(123.123), d: 0, o: '123' },
{ v: new BigNumber(123), d: undefined, o: '123' }, { v: new BigNumber(123), d: undefined, o: '123' },
{ v: new BigNumber(30000), d: undefined, o: '30,000' }, { v: new BigNumber(30000), d: undefined, o: '30,000' },
@ -54,9 +37,9 @@ describe('number react-helpers', () => {
}); });
it.each([ it.each([
{ v: new BigNumber(123), d: 3, o: '123.000%' }, { v: new BigNumber(123), d: 3, o: '123.00%' },
{ v: new BigNumber(123.123), d: 3, o: '123.123%' }, { v: new BigNumber(123.123), d: 3, o: '123.123%' },
{ v: new BigNumber(123.123), d: 6, o: '123.123000%' }, { v: new BigNumber(123.123), d: 6, o: '123.123%' },
{ v: new BigNumber(123.123), d: 0, o: '123%' }, { v: new BigNumber(123.123), d: 0, o: '123%' },
{ v: new BigNumber(123), d: undefined, o: '123.00%' }, // it default to 2 decimal places { v: new BigNumber(123), d: undefined, o: '123.00%' }, // it default to 2 decimal places
{ v: new BigNumber(30000), d: undefined, o: '30,000.00%' }, { v: new BigNumber(30000), d: undefined, o: '30,000.00%' },
@ -70,15 +53,15 @@ describe('toNumberParts', () => {
it.each([ it.each([
{ v: null, d: 3, o: ['0', '000'] }, { v: null, d: 3, o: ['0', '000'] },
{ v: undefined, d: 3, o: ['0', '000'] }, { v: undefined, d: 3, o: ['0', '000'] },
{ v: new BigNumber(123), d: 3, o: ['123', '000'] }, { v: new BigNumber(123), d: 3, o: ['123', '00'] },
{ v: new BigNumber(123.123), d: 3, o: ['123', '123'] }, { v: new BigNumber(123.123), d: 3, o: ['123', '123'] },
{ v: new BigNumber(123.123), d: 6, o: ['123', '123000'] }, { v: new BigNumber(123.123), d: 6, o: ['123', '123'] },
{ v: new BigNumber(123.123), d: 0, o: ['123', ''] }, { v: new BigNumber(123.123), d: 0, o: ['123', ''] },
{ v: new BigNumber(123), d: undefined, o: ['123', '000000000000000000'] }, { v: new BigNumber(123), d: undefined, o: ['123', '00'] },
{ {
v: new BigNumber(30000), v: new BigNumber(30000),
d: undefined, d: undefined,
o: ['30,000', '000000000000000000'], o: ['30,000', '00'],
}, },
])('returns correct tuple given the different arguments', ({ v, d, o }) => { ])('returns correct tuple given the different arguments', ({ v, d, o }) => {
expect(toNumberParts(v, d)).toStrictEqual(o); expect(toNumberParts(v, d)).toStrictEqual(o);

View File

@ -6,6 +6,7 @@ import React from 'react';
import { getUserLocale } from './utils'; import { getUserLocale } from './utils';
const MIN_FRACTION_DIGITS = 2;
const MAX_FRACTION_DIGITS = 20; const MAX_FRACTION_DIGITS = 20;
export function toDecimal(numberOfDecimals: number) { export function toDecimal(numberOfDecimals: number) {
@ -44,16 +45,7 @@ export const getNumberFormat = memoize((digits: number) => {
return new Intl.NumberFormat(getUserLocale()); return new Intl.NumberFormat(getUserLocale());
} }
return new Intl.NumberFormat(getUserLocale(), { return new Intl.NumberFormat(getUserLocale(), {
minimumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS), minimumFractionDigits: Math.min(Math.max(0, digits), MIN_FRACTION_DIGITS),
maximumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS),
});
});
export const getMaximumDigitsNumberFormat = memoize((digits: number) => {
if (isNil(digits) || digits < 0) {
return new Intl.NumberFormat(getUserLocale());
}
return new Intl.NumberFormat(getUserLocale(), {
maximumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS), maximumFractionDigits: Math.min(Math.max(0, digits), MAX_FRACTION_DIGITS),
}); });
}); });
@ -76,20 +68,6 @@ export const formatNumber = (
return getNumberFormat(formatDecimals).format(Number(rawValue)); return getNumberFormat(formatDecimals).format(Number(rawValue));
}; };
/** normalizeFormatNumber will format the number with fixed decimals, but without insignificant trailing zeros
* @param rawValue - should be a number that is not outside the safe range fail as in https://mikemcl.github.io/bignumber.js/#toN
* @param formatDecimals - number of decimals to use
*/
export const normalizeFormatNumber = (
rawValue: string | number | BigNumber,
formatDecimals = 0
): string => {
const numberToFormat = getMaximumDigitsNumberFormat(formatDecimals).format(
new BigNumber(rawValue).toNumber()
);
return numberToFormat;
};
export const addDecimalsFormatNumber = ( export const addDecimalsFormatNumber = (
rawValue: string | number, rawValue: string | number,
decimalPlaces: number, decimalPlaces: number,
@ -100,15 +78,6 @@ export const addDecimalsFormatNumber = (
return formatNumber(x, formatDecimals); return formatNumber(x, formatDecimals);
}; };
export const addDecimalsNormalizeNumber = (
rawValue: string | number,
decimalPlaces: number,
formatDecimals: number = decimalPlaces
) => {
const x = addDecimal(rawValue, decimalPlaces);
return normalizeFormatNumber(x, formatDecimals);
};
export const formatNumberPercentage = (value: BigNumber, decimals?: number) => { export const formatNumberPercentage = (value: BigNumber, decimals?: number) => {
const decimalPlaces = const decimalPlaces =
typeof decimals === 'undefined' ? Math.max(value.dp() || 0, 2) : decimals; typeof decimals === 'undefined' ? Math.max(value.dp() || 0, 2) : decimals;

View File

@ -1,7 +1,7 @@
import { Schema } from '@vegaprotocol/types'; import { Schema } from '@vegaprotocol/types';
import type { ICellRendererParams } from 'ag-grid-community'; import type { ICellRendererParams } from 'ag-grid-community';
import classNames from 'classnames'; import classNames from 'classnames';
import { addDecimalsNormalizeNumber } from '../format'; import { addDecimalsFormatNumber } from '../format';
export const Size = ({ export const Size = ({
value, value,
@ -26,7 +26,7 @@ export const Size = ({
: side === Schema.Side.SIDE_SELL : side === Schema.Side.SIDE_SELL
? '-' ? '-'
: ''} : ''}
{addDecimalsNormalizeNumber(value, positionDecimalPlaces)} {addDecimalsFormatNumber(value, positionDecimalPlaces)}
</span> </span>
); );
}; };

View File

@ -10,12 +10,12 @@ describe('PriceChangeCell', () => {
/> />
); );
expect(screen.getByText('-48.51%')).toBeInTheDocument(); expect(screen.getByText('-48.51%')).toBeInTheDocument();
expect(screen.getByText('-22.100')).toBeInTheDocument(); expect(screen.getByText('-22.10')).toBeInTheDocument();
}); });
it('renders correctly and calculates the price change without decimals', () => { it('renders correctly and calculates the price change without decimals', () => {
render(<PriceCellChange candles={['45556', '678678', '23456']} />); render(<PriceCellChange candles={['45556', '678678', '23456']} />);
expect(screen.getByText('-48.51%')).toBeInTheDocument(); expect(screen.getByText('-48.51%')).toBeInTheDocument();
expect(screen.getByText('-22,100.000')).toBeInTheDocument(); expect(screen.getByText('-22,100.00')).toBeInTheDocument();
}); });
}); });

View File

@ -10,6 +10,7 @@
"test:all": "nx run-many --all --target=test", "test:all": "nx run-many --all --target=test",
"build:all": "nx run-many --all --target=build", "build:all": "nx run-many --all --target=build",
"lint:all": "nx run-many --all --target=lint", "lint:all": "nx run-many --all --target=lint",
"e2e:all": "nx run-many --all --target=e2e",
"vegacapsule": "vegacapsule network bootstrap --config-path=../frontend-monorepo/vegacapsule/config.hcl" "vegacapsule": "vegacapsule network bootstrap --config-path=../frontend-monorepo/vegacapsule/config.hcl"
}, },
"engines": { "engines": {