Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  154] [ 1]  / answers: 1 / hits: 58323  / 9 Years ago, sun, february 8, 2015, 12:00:00

Let me give you an example.



var a = 2.0;
var stringA = + a;


I will get: stringA = 2, but I want: stringA = 2.0.



I don't want to lose precision however, so if:



var b = 2.412;
var stringB = + b;


I want to get the standard: stringB = 2.412.



That's why toFixed() won't work here. Is there any other way to do it, than to explicitly check for whole numbers like this?:



if (a % 1 === 0)
return + a + .0;
else
return + a;

More From » javascript

 Answers
17

If you want to append .0 to output from a Number to String conversion and keep precision for non-integers, just test for an integer and treat it specially.



function toNumberString(num) { 
if (Number.isInteger(num)) {
return num + .0
} else {
return num.toString();
}
}

Input Output
3 3.0
3.4567 3.4567

[#67906] Thursday, February 5, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jocelyntrishar

Total Points: 48
Total Questions: 96
Total Answers: 83

Location: South Sudan
Member since Sun, Jul 11, 2021
3 Years ago
;