I used to use String
function to convert number to string, but I found for the case like 1.0, the result is "1" but I expect to "1.0". I know 1 and 1.0 are essentially the same in Javascript. but how do you usually patch it to support my case?
UPDATE:
Please don't misunderstand my question that I want to keep the other default behavior of String
which means toFixed
is not right solution.
e.g.
1 ==> "1"
1.0 ==> "1.0"
1.00 ==> "1.00"
1.2334 ==> "1.2334"
I used to use String
function to convert number to string, but I found for the case like 1.0, the result is "1" but I expect to "1.0". I know 1 and 1.0 are essentially the same in Javascript. but how do you usually patch it to support my case?
UPDATE:
Please don't misunderstand my question that I want to keep the other default behavior of String
which means toFixed
is not right solution.
e.g.
1 ==> "1"
1.0 ==> "1.0"
1.00 ==> "1.00"
1.2334 ==> "1.2334"
Share
Improve this question
edited Jan 8, 2015 at 7:44
LeoShi
asked Jan 8, 2015 at 7:27
LeoShiLeoShi
1,8572 gold badges16 silver badges25 bronze badges
1
-
4
There's no way to distinguish between
1
and1.0
. Hence there's no function that would convert both1
to"1"
and1.0
to"1.0"
without some additional information. – Aadit M Shah Commented Jan 8, 2015 at 7:41
3 Answers
Reset to default 6You can use the "toFixed" function to do that, e.g.:
var num = 1.2345;
var n = num.toFixed(1);
You can bine this with a check to see if the number is an integer:
function numToString(num)
{
if (num % 1 === 0)
return num.toFixed(1);
else
return num.toString();
}
This is impossible without reading the source code since 1
, 1.0
, 1.00
etc all evaluate to 1.
What about a really dirty and quick solution:
var x = 1.23456;
var str = "" + x;
console.log( str );
console.log( typeof str );
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745553824a4632699.html
评论列表(0条)