0

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.

Joelgullander
  • 1,624
  • 2
  • 20
  • 46

3 Answers3

1

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 ) );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

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.

Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

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;
SReject
  • 3,774
  • 1
  • 25
  • 41