]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-main/angular/number-formatter.pipe.ts
show first decimal for views above a thousand (#3564)
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-main / angular / number-formatter.pipe.ts
1 import { Pipe, PipeTransform } from '@angular/core'
2
3 // Thanks: https://github.com/danrevah/ngx-pipes/blob/master/src/ng-pipes/pipes/math/bytes.ts
4
5 @Pipe({ name: 'myNumberFormatter' })
6 export class NumberFormatterPipe implements PipeTransform {
7 private dictionary: Array<{max: number, type: string}> = [
8 { max: 1000, type: '' },
9 { max: 1000000, type: 'K' },
10 { max: 1000000000, type: 'M' }
11 ]
12
13 /**
14 * @param x number
15 * @param n number of decimals to get (defaults to 1, needs to be >= 1)
16 */
17 static getDecimalForNumber (x: number, n = 1) {
18 const v = x.toString().split('.')
19 const f = v[1] || ''
20 if (f.length > n) return +f.substr(0, n)
21 return +f
22 }
23
24 transform (value: number) {
25 const format = this.dictionary.find(d => value < d.max) || this.dictionary[this.dictionary.length - 1]
26 const calc = value / (format.max / 1000)
27 const integralPart = Math.floor(calc)
28 const decimalPart = NumberFormatterPipe.getDecimalForNumber(calc)
29
30 return integralPart < 10 && decimalPart > 0
31 ? `${integralPart}.${decimalPart}${format.type}`
32 : `${integralPart}${format.type}`
33 }
34 }