2016-07-07 11 views

答えて

0

を変換する1行のコードを持っていると思います。ここでは、あなたが望むことをする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' 
+0

は、男 – webdeb

+0

は、この方法でより多くのをやっていますそれは必要以上に働きます。簡単な答えがあります。 – 4castle

+0

@ 4castle質問はあなたの答えのどちらも1ライナーを求めました。 – btraas

0

それは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());

+0

toLocaleStringのサポートは非​​常に現代的なブラウザです。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_compatibility – epascarello

+0

@epascarello互換性を高めるために別の答えを追加しました。 – 4castle

0

あなたは簡単にそれが生成されます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));

関連する問題