-2

In my html page I have the div below and am doing some formatting

        <div class="diffhrs">
              <span class="lbl">Hours Left: </span>
              <span class="data">@String.Format("{0:0.0#}", Model.DiffHours)</span>
        </div>

When I look at the html rendered I get this. Note that it is 3.0

        <span class="data">3.0</span>

I have the line of code below in the click event of a button, same page. when I try to read the text in the div below I get 3.03 back.

        var ProductionHoursEntered = parseFloat($('div.diffhrs .data').text());

Do you know what is happening? where is the .03 coming from?

var ProductionHoursEntered = parseFloat($('div.diffhrs .data').text());
console.log(ProductionHoursEntered);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="diffhrs">
  <span class="lbl">Hours Left: </span>
  <span class="data">@String.Format("{0:0.0#}", Model.DiffHours)</span>
</div>
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
Baba
  • 2,059
  • 8
  • 48
  • 81

2 Answers2

2

The problem is that you have multiple elements that match 'div.diffhrs .data' and if you call .text() on them, jQuery will concatenate their contents. You basically get something like "3.03.04.05.0"; parsing this as float gives 3.03.

The fix is to use

parseFloat($('div.diffhrs .data').eq(0).text());
  • Upvoted, but re: your fix . . . assuming that he wants the first one . . . otherwise, he should probably modify the jQuery selector to make the selection more specific. – talemyn Jan 11 '17 at 19:06
  • This solution fixed it. Appreciate it. – Baba Jan 11 '17 at 19:08
  • @talemyn Exactly. Assumed that to be self-evident. –  Jan 11 '17 at 19:30
0

Try adding a radix to your parseFloat method, to ensure you are returning a decimal value.

parseFloat('3.0',10);
Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63
  • Didn't downvoted your answer, but: http://stackoverflow.com/questions/8555649/second-argument-to-parsefloat-in-javascript – sinisake Jan 11 '17 at 19:03
  • I did, because it doesn't solve the problem and therefore wasn't tested. –  Jan 11 '17 at 19:04
  • How do you know it wasn't tested? It does work. It just doesn't happen to solve the persons problem because that's not the cause of it, which I can't possibly know without more information of the source code. – Steve Tomlin Jan 11 '17 at 19:09