@@ -2,28 +2,34 @@ import React from 'react';
2
2
import PropTypes from 'prop-types' ;
3
3
import styles from './NumericDisplay.module.css' ;
4
4
5
- function formatNumber ( number ) {
5
+ function formatNumber ( number , shortForm = true ) {
6
6
//format number to short form with numeric prefixes
7
- const exponent = Math . floor ( Math . log10 ( number ) ) ;
8
- const exponent3 = Math . floor ( exponent / 3 ) * 3 ;
9
- const prefixes = [ '' , 'K' , 'M' , 'B' , 'T' ] ;
10
- if ( number < 1000 ) {
11
- return number . toString ( ) ;
7
+ if ( shortForm ) {
8
+ //if short form is true
9
+ const exponent = Math . floor ( Math . log10 ( Math . abs ( Math . max ( number , 1 ) ) ) ) ; //exponent component of number
10
+ const exponent3 = Math . floor ( exponent / 3 ) * 3 ; //exponent with multiple of 3 for engineering notation
11
+ const prefixes = [ "" , "K" , "M" , "B" , "T" ] ; //numeric prefixes
12
+ if ( Math . abs ( number < 1000 ) ) {
13
+ //if number is less than 1 thousand
14
+ return Math . round ( number ) . toString ( ) ; //return number rounded to nearest integer
15
+ } else {
16
+ const roundedNumber = number . toPrecision ( 3 ) ; //round number to 3 significant figures
17
+ return (
18
+ ( parseFloat ( roundedNumber ) / Math . pow ( 10 , exponent3 ) ) . toPrecision ( 3 ) +
19
+ prefixes [ exponent3 / 3 ]
20
+ ) ; //return coefficient of engineering notation with numeric prefix
21
+ }
12
22
} else {
13
- const roundedNumber = number . toPrecision ( 3 ) ;
14
- return (
15
- ( parseFloat ( roundedNumber ) / Math . pow ( 10 , exponent3 ) ) . toPrecision ( 3 ) +
16
- prefixes [ exponent3 / 3 ]
17
- ) ;
23
+ return number . toString ( ) ;
18
24
}
19
25
}
20
26
const NumericDisplay = (
21
- { value } , //display numeric values
27
+ { value, shortForm } , //display numeric values
22
28
) => (
23
29
< span className = { styles . NumericDisplay } data-testid = "NumericDisplay" >
24
30
{ /*display numeric values with specified styles*/ }
25
- { formatNumber ( value ) }
26
- { /*bold the numeric value with short exponential form (engineering notation)*/ }
31
+ { formatNumber ( value , shortForm ) }
32
+ { /*bold the numeric value display with short exponential form (engineering notation) if short form is true */ }
27
33
</ span >
28
34
) ;
29
35
0 commit comments