admin管理员组文章数量:1430494
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 );
本文标签: javascript how to convert number 10 to string quot10quotStack Overflow
版权声明:本文标题:javascript how to convert number 1.0 to string "1.0"? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745553823a2663065.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论