Lets say I have
const Price = 279.95;
I want to get out the fraction like below:
const value = 279;
const fraction = 95;
How would I accomplish this? Fraction should always be 2 decimals.
Lets say I have
const Price = 279.95;
I want to get out the fraction like below:
const value = 279;
const fraction = 95;
How would I accomplish this? Fraction should always be 2 decimals.
You can split
by .
after converting the number to String
var getItems = ( num ) => String(num).split(".");
var splitNum = ( num ) => ( items = getItems( num ), { integer : Number(items[0]), fraction : Number(items[1] || 0) } );
console.log( splitNum( 279.95 ) );
Demo
var getItems = ( num ) => String(num).split(".");
var splitNum = ( num ) => ( items = getItems( num ), { integer : Number(items[0]), fraction : Number(items[1] || 0) } );
console.log( splitNum( 279.95 ) );
console.log( splitNum( 279 ) );
You can do it by using a simple math,
const Price = 279.95;
const value = ~~Price;
const fraction = ~~Math.ceil(((Price - value) * 100));
console.log(value); // 279
console.log(fraction); // 95
You can get more information about ~~
here.
For a set number of decimal places:
const price = 279.95;
// Double bitwise NOT; Quicker way to do Math.floor(price)
const value = ~~price;
// Remove the interger part from the price
// then multiply by 100 to remove decimal
const fraction = Math.ceil((price - value) * 100);
console.log(value, fraction)
If you want to support an arbitrary number of decimal places use this to get the fraction
:
// Convert the number to a string
// split the string into an array, delimited by "."
// get the second item(index: 1) from the array
const fraction = String(price).split(".")[1] || 0;