问题描述
第一次使用stackoverflow,但是在重建此字符串时我确实需要帮助。
所以基本上它是在Actionscript中使用的,我需要重构 Millions 字符串以将其输出为1.23M,AKA包含数以百万计的字符串,旁边还有数千个,因为目前它仅显示 1M 强>。我听说toFixed可以解决这个问题,但是我似乎无法使其正常工作。
任何示例都会有所帮助,谢谢!
public static function balancetoString(value:int):String
{
var suffix:String = "";
var resultValue:int = value;
if (value >= 1000000)
{
resultValue = Math.floor(resultValue / 1000000);
resultValue.toFixed(4);
suffix = "M";
}
else if (value >= 100000)
{
resultValue = Math.floor(resultValue / 1000);
suffix = "K";
}
return "" + resultValue.toString() + suffix;
}
解决方法
您正在将签名中的数字转换为int。
尝试使用数字代替。
public static function balanceToString(value:Number):String
{
var suffix:String = "";
var resultValue:Number = value;
if (value >= 1000000)
{
resultValue = Math.floor(resultValue / 1000000);
resultValue.toFixed(4);
suffix = "M";
}
else if (value >= 100000)
{
resultValue = Math.floor(resultValue / 1000);
suffix = "K";
}
return "" + resultValue.toString() + suffix;
}
,
我猜是这样的。
实施:
public static function balanceToString(value:int):String
{
var suffix:String = "";
var divisor:Number = 1;
var precision:Number = 0;
if (value >= 100000)
{
// This will display 123456 as 0.12M as well.
divisor = 1000000;
precision = 2;
suffix = "M";
}
else if (value >= 500)
{
// This will display 543 as 0.5K.
divisor = 1000;
precision = 1;
suffix = "K";
}
// This allows you to control,how many digits to display after
// the dot . separator with regard to how big the actual number is.
precision = Math.round(Math.log(divisor / value) / Math.LN10) + precision;
precision = Math.min(2,Math.max(0,precision));
// This is the proper use of .toFixed(...) method.
return (value / divisor).toFixed(precision) + suffix;
}
用法:
trace(balanceToString(12)); // 12
trace(balanceToString(123)); // 123
trace(balanceToString(543)); // 0.5K
trace(balanceToString(567)); // 0.6K
trace(balanceToString(1234)); // 1.2K
trace(balanceToString(12345)); // 12K
trace(balanceToString(123456)); // 0.12M
trace(balanceToString(1234567)); // 1.23M
trace(balanceToString(12345678)); // 12.3M
trace(balanceToString(123456789)); // 123M