automonous
automonous

Reputation: 55

Read a number value from a div element and round to 2 decimal places

I want to retrive a number value from a div and then round that number to 2 decimal places using jQuery.

So far I have the element name and value:

<div class="value">Price = £133.3223443</div>

I am using the toFixed() method to convert a number into a string then round to 2 decimal places:

var inNum = 12345.6789;
inNum.toFixed(2);

However, I am having trouble trying to read a number within the element on the page (ignoring 'Price'), rather than just rounding a number entered within the jQuery.

Upvotes: 0

Views: 2747

Answers (3)

Rajesh Madhu
Rajesh Madhu

Reputation: 679

The following regular expression will extract the floating numbers from the string and do a toFixed operation.

var inNum = parseFloat($(".value").text().match(/[\d\.\d]+/i)).toFixed(2);

Please make sure you have the value inside the container all the time.

Upvotes: 0

Mr.TK
Mr.TK

Reputation: 1836

Parse it with regexp? :)

http://jsfiddle.net/LERFB/2/ <--- working fiddle

    var price = $('div.value').text();
    var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
    alert(parsedPrice.toFixed(2));

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337733

You can use text() to get the value from the element, and the split() by £ to get the numerical price. Try this:

var inNum = parseFloat($('.value').text().split('£')[1]).toFixed(2);

Example fiddle

Obviously you will also need some form of verification to ensure that there is a £ character in the string to split by, and that the value retrieved is numerical.

Upvotes: 1

Related Questions