问题
Situation: I have a calculator that I'm developing using these formulas: // --- Math ---
function national(){
x = Number($('#budget').val());
y = Number($('#percentage').val());
a = x * 2;
b = [x*(100/100-(1/y))]*2;
c = (x*(1/y))*4;
d = (b+c)-a;
e = (d/a)*100;
f = (b+c);
$('#one').text(Math.round(a));
$('#two').text(Math.round(b));
$('#three').text(Math.round(c));
$('#four').text(Math.round(d));
$('#five').text(Math.round(e));
$('#six').text(Math.round(f));
$('#input1').text(Math.round(y));
$('#input2').text(Math.round(x));
}
I can't change the formatting too much because I'm using this structure use a var as a pseudo-array to feed a bar graph plugin that graphically depicts my calculations.
I have used the Math.round action to eliminate crazy calculations, but I need to add numerical formatting to the output.
I was using this regex to inset my commas
Number.prototype.format = function (f) {
return this.toString().split( /(?=(?:\d{3})+(?:\.|$))/g ).join( "," );
// ex $('#one').text(a.format());
};
but I don't know how to incorporate the regex AND Math.round action...they keep killing each other.
Problem: I need to format both my output DOM objects and my text input fields. Is this even possible and my syntax simply not appropriate, any input or possible solutions would be appreciated.
Bonus: I'm using jQuery to perform my calculations which are being dumped into spans, if there is a proper solution, could I not only incorporate said solution in my output spans, but my input text fields as well?
Cheers.
回答1:
Use this:
Number.prototype.format = function () {
return this.toString().replace(/(\d)(?=(\d{3})+$)/g, '$1,');
};
Then you could just call .format() after rounding:
$('#one').text(Math.round(a).format());
$('#two').text(Math.round(b).format());
$('#three').text(Math.round(c).format());
$('#four').text(Math.round(d).format());
$('#five').text(Math.round(e).format());
$('#six').text(Math.round(f).format());
$('#input1').text(Math.round(y).format());
$('#input2').text(Math.round(x).format());
来源:https://stackoverflow.com/questions/8761660/inserting-commas-into-numbers-for-both-objects-and-input-text-fields