简体   繁体   中英

Rounding a figure retrieved from html using javascript and jquery

I am having a little problem with rounding numbers which are brought in from html.

For example a value extracted from <input id="salesValue"> using var salesValue = $("salesValue").val() would give me a text value.

So if I did something like var doubleSalesValue = salesValue + salesValue; , it would return the number as a concatenation instead of summation of the two values.

I could use var doubleSalesValue = salesValue * 2.0; which does return the value which is to multiple decimal places. However, if I did want to use the other method, how can I approach the situation.

What methods do you use? I have created a function which I run on each number where I want to restrict the decimal places along with converting the type to number

function round(number, figure){
    return Number(Number(number).toFixed(figure));
}

I have to run Number initially to make sure that the value is converted to type number and has the method toFixed , otherwise it would throw an error here. Then I have to round the number again to the number of decimal places as required by the function, and somehow after running the toFixed method the number would sometimes turn to a string.

So, I decided to run the Number function Number(number).toFixed(figure)

Is there anything else or any different paradigm that you follow?

EDIT: I want to know if what I am doing here is conventional or are there better methods for this in general?

If you want to round it to 2 decimals you can simply do this:

var roundedNum = Math.round(parseFloat(originalNum) * 100) / 100;

Regarding your question:

and somehow after running the toFixed method the number would sometimes turn to a string.

I suggest next time read the dox a bit better https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed which says:

Returns

A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If number is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM