最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert 0 to 0.00 as number - Stack Overflow

programmeradmin1浏览0评论

I am trying to convert numbers in following formats

0 -> 0.00
1 -> 1.00
1.1 -> 1.10
4.0  -> 4.00

But problem is its returning as string only

value = 0;
var s = Math.floor(value / 60) + "." + (value % 60 ? value % 60 : '00');
console.log(s+s); //just checking if its number

But its returning as string , I tried parseInt , but its returning only 0 . I tried ParseFloat and fixedTo(2) , its returning as string only.

I am trying to convert numbers in following formats

0 -> 0.00
1 -> 1.00
1.1 -> 1.10
4.0  -> 4.00

But problem is its returning as string only

value = 0;
var s = Math.floor(value / 60) + "." + (value % 60 ? value % 60 : '00');
console.log(s+s); //just checking if its number

But its returning as string , I tried parseInt , but its returning only 0 . I tried ParseFloat and fixedTo(2) , its returning as string only.

Share Improve this question asked May 25, 2017 at 7:19 VishnuVishnu 2,4526 gold badges37 silver badges59 bronze badges 9
  • 1 If you format a number for display it bees a string. There's no other way. – Álvaro González Commented May 25, 2017 at 7:20
  • @Rajesh : it returns string – Vishnu Commented May 25, 2017 at 7:22
  • 0 and 0.00 are literals representing the same number value. You cannot get a Number literal by definition; only a string. It's not clear, though, what exactly you're trying to do here. – raina77ow Commented May 25, 2017 at 7:24
  • You can convert the string into number using the Number function i.e. Number('1.10') return 1.1 as number, but you cannot maintain the format you want. – Max Commented May 25, 2017 at 7:25
  • why do you need this kind of "numbers"? – Nina Scholz Commented May 25, 2017 at 7:26
 |  Show 4 more ments

1 Answer 1

Reset to default 11

As seen in the ments, there is no way for that in JavaScript. Formatting a Number always returns a Srting. For this you have some possibilities, though

Number(1).toFixed(2) // "1.00" - setting the number of digits after the decimal point
Number(1).toPrecision(2) // "1.0" - setting the number of digits

These are for printing it out, so normally, it shouldn't matter if it is a String or a Number.

Then if you want to use it as a Number, you just follow @Max 's advice and convert it using the function Number(str) or the shorthand +str.

发布评论

评论列表(0)

  1. 暂无评论