我有一个浮动,例如1377.5我希望在这个结构中使用纯JavaScript进行拆分:
<span class="digitLarge digit1">1</span>
<span class="digitLarge digit3">3</span>
<span class="digitLarge digit7">7</span>
<span class="digitLarge digit7">7</span>
<span class="digitPoint">.</span>
<span class="digitSmall digit5">5</span>
<span class="digitSmall digit0">0</span>
我尝试了类似的东西:
parseFloat(myFloat).toFixed(2).replace(/(.*)/g,'$1');
但是在这里我不能在点之前分裂=大而后点=小。我当然可以添加多个RegExes,但这有点不方便......
实现这一目标的最佳方法是什么?
谢谢!
干杯, 汤姆
答案 0 :(得分:0)
为什么不使用:
var number = 1377.50;
var splitted = String(number).split(".");
var beforePoint = splitted[0];
var afterPoint = splitted[0];
之后:
for(var i=0; i<beforePoint.length; i++){
var span = document.createElement("span");
span.innerHTML=beforePoint[i];
span.className="myClass";
document.body.appendChild(span);
}
var pointSpan = document.createElemnt("span");
pointSpan.innerHTML=".";
pointSpan.className="myClass";
document.body.appendChild(pointSpan);
for(var i=0; i<afterPoint.length; i++){
var span = document.createElement("span");
span.innerHTML=afterPoint[i];
span.className="myClass";
document.body.appendChild(span);
}
答案 1 :(得分:0)
您可以将float
分成数字和小数,如下所示:
var a = 12345.67;
var lg = a.toString().split(".")[0]; ///before
var sm = a.toString().split(".")[1]; ///after
alert("large: " + lg + " small: " + sm);
//if you want to further split large
alert(lg.split(""));
答案 2 :(得分:0)
var myFloat = 1377.5,
html = '',
dotReached = false;
myFloat = parseFloat(myFloat).toFixed(2);
for (var i = 0, l = myFloat.length; i < l; i++) {
if ('.' === myFloat[i]) {
html += '<span class="digitPoint">.</span>';
dotReached = true;
continue;
}
html += '<span class="' + (dotReached ? 'digitSmall' : 'digitLarge') + ' digit' + myFloat[i] + '">' + myFloat[i] + '</span>'
}
console.info(html);