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 and 1.0. Hence there's no function that would convert both 1 to "1" and 1.0 to "1.0" without some additional information. – Aadit M Shah Commented Jan 8, 2015 at 7:41
Add a ment  | 

3 Answers 3

Reset to default 6

You 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