Leon Gaban
Leon Gaban

Reputation: 39034

How to floor if less than a penny, else do not

What is the best way to check if the value is a penny or under. If under return 0 else a Math.floored value.

The code below currently will return a value of $0.01 if the price_usd is something like 00.0031. What is should return is 0.

However if the value is 00.56 it should return .56 cents which is does now.

const rounder = (balance, price_usd) => round(multiply(balance, price_usd));

constructor(props) {
    super(props)
    this.state = {
        asset: props.asset,
        balance: props.balance,
        value: rounder(props.balance, props.price_usd)
    };
    this.handleChange = this.handleChange.bind(this);
}

// value: rounder(props.balance, Math.floor(props.price_usd))

Upvotes: 2

Views: 116

Answers (2)

Mohamed Abbas
Mohamed Abbas

Reputation: 2288

You can do it using this trick.

var num1 = 0.56,
    num2 = 0.0031;

console.log(Math.floor(num1 * 100) / 100); // 0.56
console.log(Math.floor(num2 * 100) / 100); // 0.00

Upvotes: 3

Prabodh M
Prabodh M

Reputation: 2252

Solution

parseFloat(Number(price_usd).toFixed(2))

Upvotes: 1

Related Questions