Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #18901 > unrolled thread

FAQ Topic - How do I format a Number as a String with exactly 2 decimal places? (2013-03-15)

Started by"FAQ server" <javascript@dotinternet.be>
First post2013-03-15 00:00 +0000
Last post2013-03-19 08:43 +0100
Articles 6 — 3 participants

Back to article view | Back to comp.lang.javascript


Contents

  FAQ Topic - How do I format a Number as a String with exactly 2 decimal places? (2013-03-15) "FAQ server" <javascript@dotinternet.be> - 2013-03-15 00:00 +0000
    Re: FAQ Topic - How do I format a Number as a String with exactly 2 decimal places? (2013-03-15) "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2013-03-15 09:30 +0100
      Re: FAQ Topic - How do I format a Number as a String with exactly 2 decimal places? (2013-03-15) Dr J R Stockton <reply1300@merlyn.demon.co.uk.invalid> - 2013-03-16 19:57 +0000
        Re: FAQ Topic - How do I format a Number as a String with exactly 2 decimal places? (2013-03-15) "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2013-03-17 19:36 +0100
          Re: FAQ Topic - How do I format a Number as a String with exactly 2 decimal places? (2013-03-15) Dr J R Stockton <reply1300@merlyn.demon.co.uk.invalid> - 2013-03-18 19:21 +0000
            Re: FAQ Topic - How do I format a Number as a String with exactly 2 decimal places? (2013-03-15) "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2013-03-19 08:43 +0100

#18901 — FAQ Topic - How do I format a Number as a String with exactly 2 decimal places? (2013-03-15)

From"FAQ server" <javascript@dotinternet.be>
Date2013-03-15 00:00 +0000
SubjectFAQ Topic - How do I format a Number as a String with exactly 2 decimal places? (2013-03-15)
Message-ID<51426487$0$32115$14726298@news.sunsite.dk>
-----------------------------------------------------------------------
FAQ Topic - How do I format a Number as a String with
exactly 2 decimal places?
-----------------------------------------------------------------------

When formatting money for example, to format 6.57634 to 6.58, 6.7 to
6.50, and 6 to 6.00?

Rounding of x.xx5 is unreliable, as most numbers are not represented
exactly. See also:
Why does simple decimal arithmetic give strange results? [ref 1]

The statement `n = Math.round(n * 100)/100` converts `n` to a `Number` value
close to a multiple of `0.01`. However, there are some problems.
Converting the number to a string `(n + "")`, does not give
trailing zeroes. Rounding numbers that are very close to `x.5`, for example,
`Math.round(0.49999999999999992)` results `1`.

ECMA-262 3rd Edition introduced `Number.prototype.toFixed`.
There are bugs in JScript 5.8 and below with certain numbers, for example
`0.007.toFixed(2)` incorrectly results `0.00`.

var numberToFixed =
(function() {
return toFixedString;

function toFixedString(n, digits) {
var unsigned = toUnsignedString(Math.abs(n), digits);
return (n < 0 ? "-" : "") + unsigned;
}

function toUnsignedString(m, digits) {
var t, s = Math.round(m * Math.pow(10, digits)) + "",
  start, end;
if (/\D/.test(s)) {
return "" + m;
}
s = padLeft(s, 1 + digits, "0");
start = s.substring(0, t = (s.length - digits));
end = s.substring(t);
if(end) {
end = "." + end;
}
return start + end; // avoid "0."
}
/**
* @param {string} input: input value converted to string.
* @param {number} size: desired length of output.
* @param {string} ch: single character to prefix to s.
*/
function padLeft(input, size, ch) {
var s = input + "";
while(s.length < size) {
s = ch + s;
}
return s;
}
})();

// Test results
document.writeln([
"numberToFixed(9e-3, 12) => " + numberToFixed(9e-3, 12),
"numberToFixed(1.255, 2) => " + numberToFixed(1.255, 2),
"numberToFixed(1.355, 2) => " + numberToFixed(1.355, 2),
"numberToFixed(0.1255, 3) => " + numberToFixed(0.1255, 3),
"numberToFixed(0.07, 2)   => " + numberToFixed(0.07, 2),
"numberToFixed(0.0000000006, 1) => " + numberToFixed(0.0000000006, 1),
"numberToFixed(0.0000000006, 0) => " + numberToFixed(0.0000000006, 0)
].join("\n"));

<URL: http://www.merlyn.demon.co.uk/js-round.htm>
<URL: http://msdn.microsoft.com/en-us/library/sstyff0z%28VS.85%29.aspx>

References:
-----------

[1] http://jibbering.com/faq/#binaryNumbers


The complete comp.lang.javascript FAQ is at
http://jibbering.com/faq/

-- 

The sendings of these daily posts are proficiently hosted
by http://www.pair.com.

[toc] | [next] | [standalone]


#18905

From"Evertjan." <exxjxw.hannivoort@inter.nl.net>
Date2013-03-15 09:30 +0100
Message-ID<XnsA18460B31AE76eejj99@194.109.133.133>
In reply to#18901
FAQ server wrote on 15 mrt 2013 in comp.lang.javascript:

> -----------------------------------------------------------------------
> FAQ Topic - How do I format a Number as a String with
> exactly 2 decimal places?
> -----------------------------------------------------------------------
> 
> When formatting money for example, to format 6.57634 to 6.58, 6.7 to
> 6.50, and 6 to 6.00?

[Negative values should be included in this specification]

function formatNumber2(n) {
   sign = (n<0) ?'-' :'';
   n = Math.abs(n * 100 + .5);
   n = Math.floor(n).toString();
   while (n.length<3) n = '0' + n;
   n = n.replace(/(\d{2})$/,'.$1');
   return sign + n;
};

//====== test: =======

var n = -.0657634;
document.write(formatNumber2(n) + '<br>');

var n = .999999;
document.write(formatNumber2(n) + '<br>');

var n = -12.01999;
document.write(formatNumber2(n) + '<br>');

var n = -0;
document.write(formatNumber2(n) + '<br>');


-- 
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

[toc] | [prev] | [next] | [standalone]


#18915

FromDr J R Stockton <reply1300@merlyn.demon.co.uk.invalid>
Date2013-03-16 19:57 +0000
Message-ID<aZewtRTO6MRRFw0Z@invalid.uk.co.demon.merlyn.invalid>
In reply to#18905
In comp.lang.javascript message <XnsA18460B31AE76eejj99@194.109.133.133>
, Fri, 15 Mar 2013 09:30:21, Evertjan. <exxjxw.hannivoort@inter.nl.net>
posted:

>FAQ server wrote on 15 mrt 2013 in comp.lang.javascript:
>
>> -----------------------------------------------------------------------
>> FAQ Topic - How do I format a Number as a String with
>> exactly 2 decimal places?
>> -----------------------------------------------------------------------
>>
>> When formatting money for example, to format 6.57634 to 6.58, 6.7 to
>> 6.50, and 6 to 6.00?
>
>[Negative values should be included in this specification]
>
>function formatNumber2(n) {
>   sign = (n<0) ?'-' :'';
>   n = Math.abs(n * 100 + .5);
>   n = Math.floor(n).toString();
>   while (n.length<3) n = '0' + n;
>   n = n.replace(/(\d{2})$/,'.$1');
>   return sign + n;
>};
>
>//====== test: =======
>
>var n = -.0657634;
>document.write(formatNumber2(n) + '<br>');
>
>var n = .999999;
>document.write(formatNumber2(n) + '<br>');
>
>var n = -12.01999;
>document.write(formatNumber2(n) + '<br>');
>
>var n = -0;
>document.write(formatNumber2(n) + '<br>');

I expect that you did not test it with n = -33, or n = null.  The one in
the FAQ is better; it does -33 correctly.  I used current Windows XP
Firefox.

Try StrS, in <http://www.merlyn.demon.co.uk/js-rndg1.htm#GC>.

-- 
 (c) John Stockton, nr London UK. Mail, see Homepage. BP7, Delphi 3 & 2006.
   <http://www.merlyn.demon.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
   <http://www.bancoems.com/CompLangPascalDelphiMisc-MiniFAQ.htm> clpdmFAQ;
   NOT <http://support.codegear.com/newsgroups/>: news:borland.* Guidelines

[toc] | [prev] | [next] | [standalone]


#18922

From"Evertjan." <exxjxw.hannivoort@inter.nl.net>
Date2013-03-17 19:36 +0100
Message-ID<XnsA186C77818CE7eejj99@194.109.133.133>
In reply to#18915
Dr J R Stockton wrote on 16 mrt 2013 in comp.lang.javascript:

> In comp.lang.javascript message <XnsA18460B31AE76eejj99@194.109.133.133>
> , Fri, 15 Mar 2013 09:30:21, Evertjan. <exxjxw.hannivoort@inter.nl.net>
> posted:
> 
>>FAQ server wrote on 15 mrt 2013 in comp.lang.javascript:
>>
>>> 
-----------------------------------------------------------------------
>>> FAQ Topic - How do I format a Number as a String with
>>> exactly 2 decimal places?
>>> 
-----------------------------------------------------------------------
>>>
>>> When formatting money for example, to format 6.57634 to 6.58, 6.7 to
>>> 6.50, and 6 to 6.00?
>>
>>[Negative values should be included in this specification]
>>
>>function formatNumber2(n) {
>>   sign = (n<0) ?'-' :'';
>>   n = Math.abs(n * 100 + .5);

The above line should be:

   n = Math.abs(n) * 100 + .5;

>>   n = Math.floor(n).toString();
>>   while (n.length<3) n = '0' + n;
>>   n = n.replace(/(\d{2})$/,'.$1');
>>   return sign + n;
>>};
>>
>>//====== test: =======
>>
>>var n = -.0657634;
>>document.write(formatNumber2(n) + '<br>');
>>
>>var n = .999999;
>>document.write(formatNumber2(n) + '<br>');
>>
>>var n = -12.01999;
>>document.write(formatNumber2(n) + '<br>');
>>
>>var n = -0;
>>document.write(formatNumber2(n) + '<br>');
> 
> I expect that you did not test it with n = -33, or n = null.  The one in
> the FAQ is better; it does -33 correctly.  I used current Windows XP
> Firefox.

No reason why it should work with null. 
Should it work for n = 'blah';,
or for n being an object?

-- 
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

[toc] | [prev] | [next] | [standalone]


#18939

FromDr J R Stockton <reply1300@merlyn.demon.co.uk.invalid>
Date2013-03-18 19:21 +0000
Message-ID<qVd8etJBl2RRFwyr@invalid.uk.co.demon.merlyn.invalid>
In reply to#18922
In comp.lang.javascript message <XnsA186C77818CE7eejj99@194.109.133.133>
, Sun, 17 Mar 2013 19:36:30, Evertjan. <exxjxw.hannivoort@inter.nl.net>
posted:


>No reason why it should work with null.
>Should it work for n = 'blah';,
>or for n being an object?

A FAQ Number formatting routine should give correct results for all
values of the type Number.  Users who have confidence (often misplaced)
that some values will not occur can simplify the code if they need to.

For pedagogical reasons, maybe the FAQ answer should include an initial
test, commented out, that the input is indeed a Number.  With your
(original) code,   formatNumber2(formatNumber2)   returns NaN, which is
not ideal.  The result of a function call should never be misleading.

My Web site includes good, indifferent, and bad formatters.

-- 
 (c) John Stockton, nr London, UK.   E-mail, see Home Page.    Turnpike v6.05.
 Website  <http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
 PAS EXE etc. : <http://www.merlyn.demon.co.uk/programs/> - see in 00index.htm
 Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.

[toc] | [prev] | [next] | [standalone]


#18942

From"Evertjan." <exxjxw.hannivoort@inter.nl.net>
Date2013-03-19 08:43 +0100
Message-ID<XnsA18858CCDC3ECeejj99@194.109.133.133>
In reply to#18939
Dr J R Stockton wrote on 18 mrt 2013 in comp.lang.javascript:

> In comp.lang.javascript message <XnsA186C77818CE7eejj99@194.109.133.133>
> , Sun, 17 Mar 2013 19:36:30, Evertjan. <exxjxw.hannivoort@inter.nl.net>
> posted:
> 
> 
>>No reason why it should work with null.
>>Should it work for n = 'blah';,
>>or for n being an object?
> 
> A FAQ Number formatting routine should give correct results for all
> values of the type Number.  Users who have confidence (often misplaced)
> that some values will not occur can simplify the code if they need to.

I do not agree at all.
 
> For pedagogical reasons, 

... examples in the faq should not concern themselves with any code that 
is not directly necessary to demonstrate the desired effect.

A FAQ is to learn form, not to copy without understanding.

> maybe the FAQ answer should include an initial
> test, commented out, that the input is indeed a Number.  With your
> (original) code,   formatNumber2(formatNumber2)   returns NaN, 

I have no idea why formatNumber(), which by definition should return a 
string, should be able to have itself as a parameter, where logic suggests 
the parameter must be a number.

> which is not ideal.  

Why?

> The result of a function call should never be misleading.

The FAQ is for teaching. Misleadingnees is a fact of programming life, and 
should be taught, even in the FAQ-examples.

The only strict necessity [see disclaimer] of a formatter is, that it 
returns a string and that it can depand on getting parameters of described 
types.

A formatter formatMyNumber(num, decs) should not test if the decs value 
realy is a number and not a text-string like "six". At least not in the 
FAQ. even while it is perfectly possible to make this function understand 
the named string and correct for spelling-errors.

The reader wants, he could add lines forbidding negative numbers less than 
-3.96, and changing those values to an informative test-string, but such 
lines should NOT be part of the FAQ, as it makes newbees wanting to learn 
something changing their primary interest away from Javascript to 
needlework.

Your pages, which nowadays would be published as blogs [don't please], are 
a much better place to show these more intricate but very usefull examples 
you propose. The FAQ could point to them where appropriate.
 
> My Web site includes good, indifferent, and bad formatters.

Quite, but subjective in judgement. 
The FAQ should give the bare example.

Disclaimer: My ideas are not necessarily the ideas of the somewhere 
university school of matheinformatics, but then again by pure chance some 
might be.

-- 
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.javascript


csiph-web