Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jan 2014
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Unhappy Trouble with setting decimal places

    This question may already have an answer here:

    Display two decimal places, no rounding 8 answers

    I'm trying to set the number of decimal places on my stock widget, so that 0.199999 would just appear as 0.19, and 1 would appear as 1.00, and 8.6543 would just appear as 8.65. What's wrong with the script as I have it?

    Here is what I've got currently...

    Code:
    var rndchange = obj.ChangeRealtime;
    Code:
    $tr.append($('<td class="'+changeClass+'">').text(rndchange.toFixed(2)|| "--"));
    This is the entire script...

    Code:
    $(function () {
        $.getJSON('http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.finance.quotes%20WHERE%20symbol%20in(%22GCF14.CMX%22%2C%22SIF14.CMX%22%2C%22PAH14.NYM%22%2C%22PLF14.NYM%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=').done(function (data) {
        console.log("data: ", data);
        console.log(data.query.results.quote);
        $.each(data.query.results.quote, function (key, obj) {
            var changeClass = '';
            var changeInPercentClass = '';
            var rndchange = obj.ChangeRealtime;
            var $tr = $('<tr/>', {
                'class': 'my-new-list'
            }).appendTo('#blk-1 table');
            $tr.append($('<td id="name" class="cells"/>').text(obj.Name.split(' ')[0] || "--"));
            $tr.append($('<td class="cells"/>').text(obj.AskRealtime || "--"));
            //$tr.append($('<td/>').text(obj.BidRealtime || "--"));
    
            (obj.Change.substr(0,1) === '+') ? changeClass = 'green' : changeClass = 'red';
    
            (obj.Change.substr(0,1) === '+') ? changeInPercentClass = 'green' : changeInPercentClass = 'red';
    
            $tr.append($('<td class="'+changeClass+'">').text(rndchange.toFixed(2)|| "--"));
            var re = /([+|-]\d\.\d\d\%)/gi;
            var rt = re.exec(obj.ChangePercentRealtime);
            $tr.append($('<td class="'+changeInPercentClass+'">').text( rt[0] || "--"));
          });
       });
    });
    Here is my fiddle: http://jsfiddle.net/thetuneupguy/JaCaH/7/

  • #2
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    At first var a=0;alert(a.toFixed(2)||'--'); // => 0.00 and not '--' !

    Then var rndchange = +obj.ChangeRealtime; would be better to force a Number with thee + sign

    Finaly, changeClass = (obj.Change.substr(0,1) === '+') ? 'green' : 'red'; // is more usual

  • #3
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,315
    Thanks
    29
    Thanked 279 Times in 273 Posts
    Quote Originally Posted by thetuneupguy View Post
    'm trying to set the number of decimal places on my stock widget, so that 0.199999 would just appear as 0.19, and 1 would appear as 1.00, and 8.6543 would just appear as 8.65. What's wrong with the script as I have it?
    007julien gave you the answer. To be more specific, obj.ChangeRealtime is a string and toFixed is a method only available to number primitives. JavaScript's automatic type conversion doesn't work in this case, so you need to explicitly convert the string to a number. Number(rndchange).toFixed(2) is a readable way of performing type conversion.

    You shouldn't be using the non-standard substr method. Use charAt instead, which is also shorter. (You can use the slice method when multiple characters are needed.)

    Also worth noting that you're generating multiple elements with the same id attribute which is forbidden in HTML. You should use a class attribute instead. You should also be using a caption element in place of your first three div elements.

    Just as a personal XMLHttpRequest/JSON exercise, I re-coded this without jQuery, fixed all of the mentioned errors, and added logic to use proper Unicode characters for the em dash and minus sign: https://patrick.dark.name/web.dev/de....processing.2/. The code seems more verbose, but it's actually not given that the jQuery and jQuery UI scripts were scrapped.

    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <?xml-stylesheet type="application/xml" href="../style.sheets/boilerplate.xslt"?>
    <html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
    	<head>
    		<title>Demo for CodingForums.com Thread 316630: Trouble with setting decimal places</title>
    		<style>
    			#commodities caption { margin-bottom: 0.25rem; border-bottom: 0.3rem solid hsla(46, 52%, 51%, 1); padding: 0.25rem 0.4rem; background-color: hsla(201, 63%, 17%, 1); color: hsla(0, 0%, 100%, 1); font-size: 1.25rem; }
    			#commodities th { padding-left: 0.4rem; text-align: left; }
    			#commodities td:last-child { padding-right: 0.4rem; }
    			#commodities .positive { color: hsla(120, 100%, 30%, 1); }
    			#commodities .negative { color: hsla(0, 100%, 40%, 1); }
    		</style>
    		<meta itemprop="external_resource" content="https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.finance.quotes%20WHERE%20symbol%20in(%22GCF14.CMX%22%2C%22SIF14.CMX%22%2C%22PAH14.NYM%22%2C%22PLF14.NYM%22)&amp;format=json&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"/>
    	</head>
    	<body>
    		<h1 id="demo.title">Demo for CodingForums.com Thread 316630: <cite>Trouble with setting decimal places</cite></h1>
    		<section id="demo.description">
    			<h1>Demo Description</h1>
    			<p>This demo demonstrates how to fetch a third‐party <abbr title="JavaScript Object Notation">JSON</abbr> object using JavaScript and dynamically convert its data into an <abbr title="Hypertext Markup Language">HTML</abbr> table.</p>
    		</section>
    		<section id="demo">
    			<h1>Demo</h1>
    			<figure id="commodities" class="suppress.container" hidden="">
    				<table class="suppress.default.backgrounds suppress.default.borders">
    					<caption>Commodities</caption>
    				</table>
    				<figcaption class="redundant">Commodities</figcaption>
    			</figure>
    			<script>
    				// <![CDATA[
    				// This script was validated at http://jshint.com/ using the following settings:
    				/* jshint browser: true, curly: true, eqeqeq: true, devel: false, forin: true, immed: true, latedef: true, noarg: true, noempty: true, nonew: true, plusplus: true, quotmark: double, undef: true, unused: strict, strict: true, trailing: true */
    				/* global XDomainRequest */
    				(function () {
    					"use strict";
    					var namespaces = Object.create(null);
    					namespaces.null = "";
    					namespaces.XHTML = "http://www.w3.org/1999/xhtml";
    					function parseCommoditiesInfo() {
    						/* jshint validthis: true */
    						var commodityInfoRequest = this;
    						var commodityInfo = null;
    						if (commodityInfoRequest instanceof XMLHttpRequest && commodityInfoRequest.readyState === XMLHttpRequest.DONE && commodityInfoRequest.statusText === "OK") {
    							commodityInfoRequest.removeEventListener("readystatechange", parseCommoditiesInfo);
    							commodityInfo = JSON.parse(commodityInfoRequest.responseText);
    							showCommoditiesInfo(commodityInfo);
    						}
    						else { // Windows Internet Explorer 9
    							commodityInfo = JSON.parse(commodityInfoRequest.responseText);
    							showCommoditiesInfo(commodityInfo);
    						}
    					}
    					function getCommoditiesInfo() {
    						document.removeEventListener("DOMContentLoaded", getCommoditiesInfo);
    						var commodityInfoRequest = null;
    						if (typeof XDomainRequest === "undefined") {
    							commodityInfoRequest = new XMLHttpRequest();
    							commodityInfoRequest.addEventListener("readystatechange", parseCommoditiesInfo);
    						}
    						else if (typeof XDomainRequest === "function") { // Windows Internet Explorer 9
    							commodityInfoRequest = new XDomainRequest();
    							commodityInfoRequest.onload = parseCommoditiesInfo;
    						}
    						commodityInfoRequest.open("get", "https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20yahoo.finance.quotes%20WHERE%20symbol%20in(%22GCF14.CMX%22%2C%22SIF14.CMX%22%2C%22PAH14.NYM%22%2C%22PLF14.NYM%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", false);
    						commodityInfoRequest.send();
    					}
    					function showCommoditiesInfo(commodityInfo) {
    						var commodityIndex = 0;
    						var commodities = commodityInfo.query.results.quote;
    						var commodity = null;
    						var figure = document.getElementById("commodities");
    						var table = figure.getElementsByTagNameNS(namespaces.XHTML, "table").item(0);
    						var row = null;
    						var nameCell = null;
    						var valueCell = null;
    						var valueAbsChangeCell = null;
    						var valuePercentChangeCell = null;
    						var name = null;
    						var value = null;
    						var valueAbsChange = null;
    						var valuePercentChange = null;
    						var valueIsNumber = /^[+\-]?(?:\d\.?|\d*\.\d+)$/;
    						while (commodityIndex < commodities.length) {
    							commodity = commodities[commodityIndex];
    							row = document.createElementNS(namespaces.XHTML, "tr");
    							nameCell = document.createElementNS(namespaces.XHTML, "th");
    							valueCell = document.createElementNS(namespaces.XHTML, "td");
    							valueAbsChangeCell = document.createElementNS(namespaces.XHTML, "td");
    							valuePercentChangeCell = document.createElementNS(namespaces.XHTML, "td");
    							name = commodity.Name.split(" ")[0];
    							value = commodity.AskRealtime;
    							valueAbsChange = commodity.ChangeRealtime;
    							valuePercentChange = commodity.ChangePercentRealtime.split(" ")[2].slice(0, -1);
    							valueCell.setAttributeNS(namespaces.null, "class", "number");
    							nameCell.textContent = name;
    							valueCell.textContent = value;
    							if (typeof valueAbsChange === "string" && valueIsNumber.test(valueAbsChange)) {
    								if (valueAbsChange.charAt(0) === "+") {
    									valueAbsChangeCell.setAttribute("class", "number positive");
    									valueAbsChange = "+" + Number(valueAbsChange).toFixed(2);
    								}
    								else {
    									valueAbsChangeCell.setAttribute("class", "number negative");
    									valueAbsChange = "−" /* U+2212 MINUS SIGN */ + Number(valueAbsChange.slice(1)).toFixed(2);
    								}
    								valueAbsChangeCell.textContent = valueAbsChange;
    							}
    							else {
    								valueAbsChangeCell.textContent = "—" /* U+2014 EM DASH */;
    							}
    							if (typeof valuePercentChange === "string" && valueIsNumber.test(valuePercentChange)) {
    								if (valuePercentChange.charAt(0) === "+") {
    									valuePercentChangeCell.setAttribute("class", "number positive");
    									valuePercentChange = "+" + Number(valuePercentChange).toFixed(2);
    								}
    								else {
    									valuePercentChangeCell.setAttribute("class", "number negative");
    									valuePercentChange = "−" /* U+2212 MINUS SIGN */ + Number(valuePercentChange.slice(1)).toFixed(2);
    								}
    								valuePercentChangeCell.textContent = valuePercentChange + "%";
    							}
    							else {
    								valuePercentChangeCell.textContent = "—" /* U+2014 EM DASH */;
    							}
    							row.appendChild(nameCell);
    							row.appendChild(valueCell);
    							row.appendChild(valueAbsChangeCell);
    							row.appendChild(valuePercentChangeCell);
    							table.appendChild(row);
    							figure.removeAttributeNS(namespaces.null, "hidden");
    							commodityIndex += 1;
    						}
    					}
    					document.addEventListener("DOMContentLoaded", getCommoditiesInfo);
    				})();
    				// ]]>
    			</script>
    		</section>
    	</body>
    </html>
    For every complex problem, there is an answer that is clear, simple, and wrong.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •