Skip to content

Instantly share code, notes, and snippets.

@whisher
Created December 23, 2019 13:28
Show Gist options
  • Save whisher/1a29014d6cbeb9c912e252a1fe402765 to your computer and use it in GitHub Desktop.
Save whisher/1a29014d6cbeb9c912e252a1fe402765 to your computer and use it in GitHub Desktop.
Module
// Core
import { NgModule, Optional, SkipSelf } from '@angular/core';
// Big.js
import Big from 'big.js/big.mjs';
import { BigjsService } from './bigjs.service';
@NgModule({
providers: [{ provide: 'BigJs', useValue: Big }, BigjsService]
})
export class CoreModule {
constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
if (parentModule) {
throw new Error('CoreModule is already loaded. Import only in AppModule');
}
}
}
//Service
import { Inject, Injectable } from '@angular/core';
import Big from 'big.js/big.mjs';
type OgBig = typeof Big;
@Injectable()
export class BigjsService {
readonly TO_FIXED = 2;
constructor(@Inject('BigJs') private bj: OgBig) {}
toStr(value: number | string | OgBig): string {
if (value instanceof Big) {
return value.toFixed(this.TO_FIXED);
}
return this.bj(value).toFixed(this.TO_FIXED);
}
op(num: number | string): OgBig {
return this.bj(num);
}
withSpread(value: string, spread: string): string {
const valueTimesPlus = this.op(value).times(this.op(100).plus(spread));
return valueTimesPlus
.div(100)
.toFixed(this.TO_FIXED)
.toString();
}
trunc(value: string, digits: number = 0): number {
const multi = Math.pow(10, digits);
const v = parseInt(value, 10);
return Math.trunc(v * multi) / multi;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment