Reputation: 278
I have a simple problem to solve, I have a variable containing a double, I'm reading in another double from user input. I need to sum the two numbers and print the result to the screen. In other languages I have worked in, just the fact that it was a double would result in it printing with a decimal, even if it is a whole number. In Javascript, this is not the case.
var d = 2.0;
console.log(d) // out is 2
I can force it to print a decimal by using toFixed()
, but then it is going to round results of other input. If the result is 2.0, I want it to print "2.0" and if the result is 2.345, I want it to print "2.345".
The solution I have right now is to convert it to a string if it is a whole number:
var d2 = 4.0
console.log((d2 % 1 == 0) ? d2+".0" : d2) // out is 4.0
I feel like there must be some better way to do this. This seems very clunky to me. I've been searching for solutions, but everything I have found so far uses toFixed()
or some other rounding.
Upvotes: 1
Views: 1969
Reputation: 1
function number(r){
const a= 4.43
const answer= a.tofixed(4)
console.log(answer)
return answer
}
Upvotes: -1
Reputation: 20870
For better dynamic printing (no useless leading zeroes) Use:
Number(num.toFixed(5)).toString()
Here an example to show the interpretation:
const num = 2.2;
console.log(
Number(num.toFixed(5)).toString()
);
// 2.2
const num = 2.2;
console.log(
num.toFixed(5)
);
// 2.20000
[Notice] You can use node interpreter to test faster and have a playground:
Upvotes: 0
Reputation: 93
Try this:
var d = 2.0;
var parsD = parseFloat(d); //you have to parse d either as Float or Integer
console.log(parsD) // out will be in decimal without rounding up
You have to decide the number of decimals. Be realistic. e.g. for financial issues, 2 decimal places is just OK. In which case change line 2 to:
var parsD = parseFloat(d).toFixed(n) //where n is an integer & number of decimals
This works fine. In my case, I receive input on a form. The input can be integer or decimal. However when processing, every input is treated as decimal.
Upvotes: 1
Reputation: 14060
I think a more Number-y solution could be:
var d = 4.0
var ds = Number.isInteger(d) ? d.toPrecision(2) : d.toString();
console.log(ds)
Upvotes: 1