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,534
  • 1
  • 17
  • 39

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
  • 64,240
  • 8
  • 67
  • 88
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
  • 20,493
  • 5
  • 36
  • 47
Rajaprabhu Aravindasamy
  • 64,912
  • 15
  • 96
  • 124
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,481
  • 1
  • 21
  • 39