Skip to content

Commit

Permalink
New: trim extra zeroes in prices
Browse files Browse the repository at this point in the history
  • Loading branch information
pustovitDmytro committed Jul 2, 2022
1 parent e428b3b commit bcc8a50
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
21 changes: 20 additions & 1 deletion src/prices/Price.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,25 @@ export default class Price {
}

get prettyPrice() {
return this.price.toFixed(this.precision).toString(); // TODO: drop trailing spaces
const str = this.price.toFixed(this.precision).toString();

if (!str.includes('.')) return str;

let trimFrom = str.length;

for (const char of [ ...str ].reverse()) {
if (char === '0') {
trimFrom--; continue;
}

if (char === '.') {
trimFrom--; break;
}

break;
}


return str.slice(0, trimFrom);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Binance from '../../src/exchanges/Binance';
const exchange = new Binance();
const factory = new Test();

suite('unit: getPrice [binance]');
suite('unit: exchange.getPrice [binance]');

before(async function () {
factory.mockAPI();
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/pricePrettyPrice.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { assert } from 'chai';
import '../Test';
import Price from '../../src/prices/Price';


suite('unit: price.prettyPrice');

test('leave good prices as is', async function () {
assert.equal((new Price(12.123_456_78)).prettyPrice, '12.12345678');
});

test('round over precision', async function () {
assert.equal((new Price(12.123_456_781)).prettyPrice, '12.12345678');
assert.equal((new Price(12.123_456_786)).prettyPrice, '12.12345679');
});

test('trim extra zeroes', async function () {
assert.equal((new Price(12.123)).prettyPrice, '12.123');
assert.equal((new Price(100)).prettyPrice, '100');
assert.equal((new Price(12)).prettyPrice, '12');
assert.equal((new Price(1.000_000_000_000_000_001)).prettyPrice, '1');
assert.equal((new Price(0.000_000_000_000_000_01)).prettyPrice, '0');
});

0 comments on commit bcc8a50

Please sign in to comment.