import { curry } from 'ramda' ; import { isExp } from './is-exp' ; import { isFloat } from './is-float' ; const floatFixed = ( _dgt , sourceNum , sourceStr ) => { const dgt = Math . max ( _dgt , 0 ) ; if ( dgt === 0 ) { return Math . round ( sourceNum ) ; } const dotIndex = sourceStr . indexOf ( '.' ) ; const digitN = sourceStr . length - ( dotIndex + 1 ) ; if ( digitN <= dgt ) { return sourceNum ; } const fixedSub = sourceStr . slice ( 0 , dotIndex + dgt + 1 ) ; if ( + sourceStr [ dotIndex + dgt + 1 ] > 4 ) { if ( /\.9+$/ . test ( fixedSub ) ) { return sourceNum < 0 ? Math . floor ( sourceNum ) : Math . ceil ( sourceNum ) ; } else { return + fixedSub . replace ( /([0-8])9*$/ , ( _mantissa , lastN ) => `${ + lastN + 1 }` ) ; } } else { return + fixedSub ; } } ; export const toFixed = curry ( ( digit , n ) : number => { if ( ! isFinite ( n ) ) { return n ; } const s = n . toString ( ) ; if ( isExp ( s ) ) { const eIndex = s . indexOf ( 'e' ) ; if ( s [ eIndex + 1 ] === '-' ) { const exp = + s . slice ( eIndex + 2 ) ; if ( digit < exp - 1 ) { return 0 ; } if ( digit === exp - 1 ) { return + `${ + s [ 0 ] > 4 ? 1 : 0 }e-${ exp - 1 }` ; } if ( isFloat ( s ) ) { if ( digit >= eIndex - ( s . indexOf ( '.' ) + 1 ) + exp ) { return n ; } const dotS = s . slice ( 0 , eIndex ) ; const dotFix = floatFixed ( digit - exp , + dotS , dotS ) ; return + `${ dotFix }e-${ exp }` ; } return n ; } else { return n ; } } if ( isFloat ( s ) ) { return floatFixed ( digit , n , s ) ; } return n ; } ) ;