Created
July 18, 2019 16:07
-
-
Save Nachasic/21259aae50d0c798b5c28edb3547b318 to your computer and use it in GitHub Desktop.
Alternative to `Math.frac()` in Javascript
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
// testing using Jest | |
import { frac } from './frac'; | |
describe('Math frac tests', () => { | |
it('should be defined', () => { | |
expect(frac).toBeDefined(); | |
}); | |
it('should accurately calculate fraction of a number', () => { | |
expect( frac(-3.1234) ).toEqual( -0.1234 ); | |
expect( frac(1.234) ).toEqual( 0.234 ); | |
expect( frac(56789e-3) ).toEqual( 0.789 ); | |
expect( frac(12345678) ).toEqual( 0 ); | |
expect( frac(-34.5697) ).toEqual( -0.5697 ); | |
}); | |
}); |
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
/** | |
* TBasically Math.frac() | |
* Alternative to less accurate hacks: | |
* ```ts | |
* const fracNum = (num: number) => num % 1; | |
* console.log( fracNum(34.5697) ) // 0.5696999999999974 in Node | |
* ``` | |
* @example const foo = frac(34.5697) // 0.569 | |
* | |
* LICENCE: MIT | |
*/ | |
export const frac = (num: number) => | |
+(num.toString()).replace( | |
Math.trunc(num).toString(), | |
'0' | |
) * Math.sign(num); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment