【问题标题】:Javascript how to convert float 2.0 to string '2.0'?Javascript如何将float 2.0转换为字符串'2.0'?
【发布时间】:2016-11-09 04:53:27
【问题描述】:

我尝试了toFixed(),但它并没有达到我想要的效果。 我想要一个可以转换的单行代码

2.0   -->   '2.0'
2.123 -->   '2.123'
0.05  -->   '0.05'

【问题讨论】:

  • 怎么样:.toString()

标签: javascript floating-point string-formatting


【解决方案1】:

基本上你想要toString(),但小数点最少 (1)。这是一个可以满足您需求的单线器。

var num = 5;

num.toFixed(Math.max(1, num.toString().substr(num.toString().indexOf(".")+1).length));

我宁愿把它放在一个函数中 -

function floatToString(num) {
    return num.toFixed(Math.max(1, num.toString().substr(num.toString().indexOf(".")+1).length));
}

用法:

floatToString(2.0)   -->   '2.0'
floatToString(2.123) -->   '2.123'
floatToString(0.05)  -->   '0.05'

【讨论】:

  • 这比它需要做的工作要多得多。有更简单的答案。
  • @4castle 这个问题要求单线,你的答案都不是。
  • 我可以将所有代码放在一行中,但我喜欢可读的代码。我们三个人都有一个使用一个分号的答案。当使用一个没有意义时,单行被高估了。
【解决方案2】:

可以通过Number#toLocaleString()完成

Number.prototype.toFloatString = function() {
  return this.toLocaleString("en-US", {
    minimumFractionDigits: 1,
    maximumFractionDigits: 20 // the default is 3 if min < 3
  });
};

console.log((2.0).toFloatString());
console.log((2.123).toFloatString());
console.log((0.05).toFloatString());

或者,只需使用toString(),如果数字是整数,则添加.0

Number.prototype.toFloatString = function() {
  var str = this.toString();
  return str.indexOf(".") < 0 ? str + ".0" : str;
};

console.log((2.0).toFloatString());
console.log((2.123).toFloatString());
console.log((0.05).toFloatString());

【讨论】:

【解决方案3】:

您可以轻松地使用toString(),它将产生预期的 .0 浮点数输出。因此,您可以使用此功能:

function floatToStr(num) {
    return num.toString().indexOf('.') === -1 ? num.toFixed(1) : num.toString();
}

演示:

function floatToStr(num) {
    return num.toString().indexOf('.') === -1 ? num.toFixed(1) : num.toString();
}

console.log(floatToStr(2.0));
console.log(floatToStr(2.123));
console.log(floatToStr(0.05));

【讨论】:

    猜你喜欢
    • 2015-10-11
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    相关资源
    最近更新 更多