0

Possible duplicate of a similar question so sorry about that.

However, I can't seem to figure it out whether it is possible to print an integer with 0 value decimal. I have checked the https://javascript.info/number documentation still can't find an answer.

My attemps:

const sum = 1.0 + 1.0
const e = sum.toFixed(1)

console.log(e)
// string output "2.0"

const sum= 1.0 + 1.0
const e =+sum.toFixed(1)

console.log(e)
// integer output with no decimal 2

const sum= 1.0 + 1.0
const e = Number(sum.toFixed(1))

console.log(e)
// same integer output with no decimal 2

Is it possible to print an integer with a value of 2.0?

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
Ade N
  • 145
  • 1
  • 1
  • 12
  • 2
    Does this answer your question? [Format number to always show 2 decimal places](https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places) – Dokksen Aug 28 '20 at 10:01
  • 3
    What's wrong with your first snippet? That's how it should be done. – sp00m Aug 28 '20 at 10:05
  • 3
    `2.0` is not an integer ... Numbers in JS are presented according to [IEEE 754 standard](https://en.wikipedia.org/wiki/IEEE_754), leading and trailing zeros are not included. – Teemu Aug 28 '20 at 10:07
  • I guess this answers my questions. Thanks Teemu !!! – Ade N Aug 28 '20 at 10:15
  • @sp00m The first snippet doesn't return an integer .https://jsbin.com/zihahunonu/edit?js,console,output – Ade N Aug 28 '20 at 10:16
  • 1
    @AdeN You can't return `2.0` as an integer, that's not how JS represents integers. A string/float are the only ways you can display it like that (And a float will probably not show the decimal if it's `.0`) If it's for display purposes, it shouldn't mater that it's a string, and if it's for use in calculations, the format shouldn't matter. I'm having trouble understanding the problem here. – DBS Aug 28 '20 at 10:22
  • @DBS thanks for the comment. I was trying to solve this problem using JavaScript https://www.hackerrank.com/challenges/30-data-types/problem . I guess Java is better equipped to deal with this issue. – Ade N Aug 28 '20 at 10:27

1 Answers1

0

This should be your answer :

const sum= 1.0 + 1.0
const e = Number(sum.toFixed(1))
console.log(Number(e).toFixed(1))
alithecodeguy
  • 125
  • 1
  • 5
  • 2
    Why would you convert number to a string (`toFixed`), then back to a number (`Number()`), then try and convert number-number again... then back to string? The only difference between this and the asker's first snippet is a lot of unnecessary type conversion. – DBS Aug 28 '20 at 10:18
  • Using typeof before the logged value tells its a string, not Number. – roshnet Aug 28 '20 at 10:24