Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Alternative to `Math.frac()` in Javascript
// 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 );
});
});
/**
* 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