flow24
flow24

Reputation: 943

Convert whole number to one decimal in JavaScript

I got this issue. I want to convert integer 71 (type number) to one decimal, meaning 71.0

but I need it to stay of type number. Searched and the only solution I found was to use toFixed(1) and then parseFloat on the result, and that does returns a number but 71, without the decimal.

const float = (num) => {
    let fixed = (num).toFixed(1)
    let float = parseFloat(fixed)
    
    return float
}

float(71)

How should I do it?

Upvotes: 0

Views: 1626

Answers (2)

mw509
mw509

Reputation: 2093

Remove the parseFloat(fixed) and keep it as below

const float = (num) => {
    let fixed = (num).toFixed(2)
    //let float = parseFloat(fixed)
    
    return float
}

float(71)

use toFixed(n) where n is the number of 10th places after the decimal.

You have stated that you need to keep it as number at the end but the thing is, if the decimals are 0, it will always round up to a whole number. So you may want to rather consider adding the toFixed(n) at the point of printing to the screen so they always print with that extra.

========= UPDATE

I just found a cleaner solution. consider the below with a link to the solution

const float = (num) => {
    tmp = '0.00';
    tmp = (+tmp + num).toFixed(2);
    
    return tmp
}

float(71)

reference: how to get a float using parseFloat(0.00)

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

This makes no sense, because an integer (whole number) will almost always equal its floating-point equivalent, unless there is a some odd precision behavior.

  • 71 === 71.0
  • 71 === 71.00
  • ...
  • 71 !== 71.000000001

Did you want to truncate a floating number using precision?

const truncateFloat = (n, p = 0) => parseFloat(n.toFixed(p));

// Truncate an irrational number (PI)
console.log(truncateFloat(Math.PI, 2) === 3.14) // true

Upvotes: 1

Related Questions