-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (78 loc) · 2.64 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import React, { Component } from "react";
import { Platform, Text, StyleSheet } from "react-native";
export default class NumberAbbreviator extends Component {
constructor(props) {
super(props);
this.state = {
decimalsToShow: this.props.decimalsToShow, // number of decimal places to show
formattedNumber: "not received", // output
minNumberToFormat: this.props.minNumberToFormat, // length number must be >== to format
passedInNumber: this.props.passedInNumber, // number you are formatting
};
}
async componentDidMount() {
await this.abbrNum(this.state.passedInNumber, this.state.decimalsToShow); // max decimal places 4
}
abbrNum = (number, decPlaces) => {
if (number >= this.state.minNumberToFormat ) {
console.log(
"abbr num triggered with input number: " +
number +
" and decplaces: " +
decPlaces
);
// 2 decimal places => 100, 3 => 1000, etc
decPlaces = Math.pow(10, decPlaces);
// Enumerate number abbreviations
var abbrev = ["K", "M", "B", "T"];
// Go through the array backwards, so we do the largest first
for (var i = abbrev.length - 1; i >= 0; i--) {
// Convert array index to "1000", "1000000", etc
var size = Math.pow(10, (i + 1) * 3);
// If the number is bigger or equal do the abbreviation
if (size <= number) {
// Here, we multiply by decPlaces, round, and then divide by decPlaces.
// This gives us nice rounding to a particular decimal place.
number = Math.round((number * decPlaces) / size) / decPlaces;
// Handle special case where we round up to the next abbreviation
if (number == 1000 && i < abbrev.length - 1) {
number = 1;
i++;
}
// Add the letter for the abbreviation
number += abbrev[i];
console.log("formatted = ", number);
this.setState({
formattedNumber: number
});
// We are done... stop
break;
}
}
return number;
} else {
console.log(`Number smaller than ${this.state.minNumberToFormat} : ${number}`)
let formattedSmallNum = number.toLocaleString("en", {
style: "decimal",
maximumFractionDigits: 0,
minimumFractionDigits: 0
})
this.setState({
formattedNumber: formattedSmallNum
});
}
};
render() {
return (
<Text style={styles.font}>
{/* passed in number: {this.state.passedInNumber} formatted: */}
${this.state.formattedNumber}
</Text>
);
}
}
const styles = StyleSheet.create({
font: {
fontFamily: Platform.OS === "ios" ? "Avenir" : "sans-serif"
}
});