-
Notifications
You must be signed in to change notification settings - Fork 357
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(digits): l10n support for TdDigitsPipe (#378)
* feat(digits): i10n support for TdDigitsPipe leverage LOCALE_ID and DecimalPipe to support l10n within TdDigitsPipe and update unit tests * fix(): return argument if not a number * fix(): fix comment
- Loading branch information
1 parent
ec215c9
commit b060c78
Showing
2 changed files
with
36 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,32 @@ | ||
import { Pipe, PipeTransform } from '@angular/core'; | ||
import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core'; | ||
import { DecimalPipe } from '@angular/common'; | ||
|
||
@Pipe({ | ||
name: 'digits', | ||
}) | ||
|
||
export class TdDigitsPipe implements PipeTransform { | ||
|
||
private _decimalPipe: DecimalPipe; | ||
|
||
constructor(@Inject(LOCALE_ID) private _locale: string = 'en') { | ||
this._decimalPipe = new DecimalPipe(this._locale); | ||
} | ||
|
||
/* `digits` needs to be type `digits: any` or TypeScript complains */ | ||
transform(digits: any, precision: number = 1): string { | ||
if (digits === 0) { | ||
return '0'; | ||
} else if (isNaN(parseInt(digits, 10))) { | ||
/* If not a valid number, return 'Invalid Number' */ | ||
return 'Invalid Number'; | ||
} else if (digits < 1) { | ||
/* If not a valid number, return the value */ | ||
return digits; | ||
} else if (digits < 1) { | ||
return this._decimalPipe.transform(digits.toFixed(precision)); | ||
} | ||
let k: number = 1000; | ||
let sizes: string[] = ['', 'K', 'M', 'B', 'T', 'Q']; | ||
let i: number = Math.floor(Math.log(digits) / Math.log(k)); | ||
let size: string = sizes[i]; | ||
return parseFloat((digits / Math.pow(k, i)).toFixed(precision)) + (size ? ' ' + size : ''); | ||
return this._decimalPipe.transform(parseFloat((digits / Math.pow(k, i)).toFixed(precision))) + (size ? ' ' + size : ''); | ||
} | ||
} |