473,418 Members | 2,099 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,418 software developers and data experts.

FAQ Topic - How do I convert a Number into a String with exactly 2 decimal places? (2008-06-20)

-----------------------------------------------------------------------
FAQ Topic - How do I convert a Number into a String with
exactly 2 decimal places?
-----------------------------------------------------------------------

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

Rounding of x.xx5 is uncertain, as such numbers are not
represented exactly. See section 4.7 for Rounding issues.

N = Math.round(N*100)/100 only converts N to a Number of value
close to a multiple of 0.01; but document.write(N) does not give
trailing zeroes.

ECMAScript Ed. 3.0 (JScript 5.5 [but buggy] and JavaScript 1.5)
introduced N.toFixed, the main problem with this is the bugs in
JScripts implementation.

Most implementations fail with certain numbers, for example 0.07.
The following works successfully for M>0, N>0:

Expand|Select|Wrap|Line Numbers
  1. function Stretch(Q, L, c) { var S = Q
  2. if (c.length>0) while (S.length<L) { S = c+S }
  3. return S
  4. }
  5. function StrU(X, M, N) { // X>=0.0
  6. var T, S=new String(Math.round(X*Number("1e"+N)))
  7. if (S.search && S.search(/\D/)!=-1) { return ''+X }
  8. with (new String(Stretch(S, M+N, '0')))
  9. return substring(0, T=(length-N)) + '.' + substring(T)
  10. }
  11. function Sign(X) { return X>0 ? "+" : X<0 ? "-" : " " }
  12. function StrS(X, M, N) { return Sign(X)+StrU(Math.abs(X), M, N) }
  13. Number.prototype.toFixed = function(n){ return StrS(this,1,n) };
http://www.merlyn.demon.co.uk/js-round.htm

http://msdn2.microsoft.com/en-us/library/sstyff0z.aspx


--
Postings such as this are automatically sent once a day. Their
goal is to answer repeated questions, and to offer the content to
the community for continuous evaluation/improvement. The complete
comp.lang.javascript FAQ is at http://jibbering.com/faq/index.html.
The FAQ workers are a group of volunteers. The sendings of these
daily posts are proficiently hosted by http://www.pair.com.
Jun 27 '08 #1
10 1825
FAQ server wrote on 20 jun 2008 in comp.lang.javascript:
-----------------------------------------------------------------------
FAQ Topic - How do I convert a Number into a String with
exactly 2 decimal places?
-----------------------------------------------------------------------
I would like to add my latest version for 'any' integer d >= 0:

Expand|Select|Wrap|Line Numbers
  1. function round(n,d){
  2. n = Math.floor(n*Math.pow(10,d)+.5);
  3. if (d<1) return n;
  4. var s = Math.abs(n).toString();
  5. while (s.length<d+1) s = '0' + s;
  6. return ((n<0) ?'-':'') + s.slice(0,-d) + '.' + s.slice(-d);
  7. };
I do not trust internal rounding to be according to my definition.
I like the slice() string manpulation possibilities.

Shoot?

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jun 27 '08 #2
You should write this...

Expand|Select|Wrap|Line Numbers
  1. var numberObj = new Number(6.57634);
  2. var formattedNumber = numberObj.toFixed(2);

Graham
Jun 27 '08 #3
yukabuk wrote on 20 jun 2008 in comp.lang.javascript:
You should write this...

var numberObj = new Number(6.57634);
var formattedNumber = numberObj.toFixed(2);
You? Why?

What are you responding on?

[please always quote on usenet]

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jun 27 '08 #4
In comp.lang.javascript message <Xn********************@194.109.133.242>
, Fri, 20 Jun 2008 13:26:35, Evertjan. <ex**************@interxnl.net>
posted:
>FAQ server wrote on 20 jun 2008 in comp.lang.javascript:
>-----------------------------------------------------------------------
FAQ Topic - How do I convert a Number into a String with
exactly 2 decimal places?
-----------------------------------------------------------------------

I would like to add my latest version for 'any' integer d >= 0:
Fails, I think, for n=1.11, d>21 ; also for n = infinity, NaN. Put your
function, followed by return round(X, N) in the second textarea of
<URL:http://www.merlyn.demon.co.uk/js-round.htm#TRPFand press the
button.
>function round(n,d){
n = Math.floor(n*Math.pow(10,d)+.5);
if (d<1) return n;
var s = Math.abs(n).toString();
while (s.length<d+1) s = '0' + s;
return ((n<0) ?'-':'') + s.slice(0,-d) + '.' + s.slice(-d);
};

I do not trust internal rounding to be according to my definition.
I like the slice() string manpulation possibilities.

Shoot?
The one in the FAQ includes provision for a fixed number of places, or
characters, before the decimal separator, which is useful for tables in
<pre>, etc.

It would be nicer, for those who recall FORTRAN convention, to use x
instead of n. And, to please IUPAP/SUNAMCO. .5 should be 0.5 .

Note that I don't use what the FAQ says.

--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demon.co.uk/clpb-faq.txt RAH Prins : c.l.p.b mFAQ;
<URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zipTimo Salmi's Turbo Pascal FAQ.
Jun 27 '08 #5
Dr J R Stockton wrote on 20 jun 2008 in comp.lang.javascript:
>>I would like to add my latest version for 'any' integer d >= 0:

Fails, I think, for n=1.11, d>21 ; also for n = infinity, NaN.
With quoted 'any', I ment any reasonable. ;-)

Catching all possibilities makes the code sound but unreadable for
instruction.
Put your
function, followed by return round(X, N) in the second textarea of
<URL:http://www.merlyn.demon.co.uk/js-round.htm#TRPFand press the
button.
Sorry, John, your server seems down.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jun 27 '08 #6
On Jun 21, 8:53*am, "Evertjan." <exjxw.hannivo...@interxnl.netwrote:
Dr J R Stockton wrote on 20 jun 2008 in comp.lang.javascript:
>I would like to add my latest version for 'any' integer d >= 0:
Fails, I think, for n=1.11, d>21 ; also for n = infinity, NaN. *

With quoted 'any', I ment any reasonable. ;-)

Catching all possibilities makes the code sound but unreadable for
instruction.
It is only necessary to include a test that s is all-digit, such as
if (/\D/.test(d)) return n // cannot cope

IMHO, d=0 should be allowed; it should give results such as "3." which
is deprecated but not wrong.

Sorry, John, your server seems down.
<QUOTE>
We will be carrying out planned maintenance of our Web Hosting
platform as follows:
Saturday 21st June between 00:01 and 20:00 Hrs BST
Saturday 28th June between 00:01 and 04:00 Hrs BST
Sunday 29th June between 00:01 and 04:00 Hrs BST
</QUOTE>

--
(c) John Stockton, near London, UK. Posting with Google.
Mail: J.R.""""""""@physics.org or (better) via Home Page at
Web: <URL:http://www.merlyn.demon.co.uk/>
FAQish topics, acronyms, links, etc.; Date, Delphi, JavaScript, ...

Jun 27 '08 #7
On Jun 19, 4:00*pm, "FAQ server" <javascr...@dotinternet.bewrote:

[snip]
ECMAScript Ed. 3.0 (JScript 5.5 [but buggy] and JavaScript 1.5)
introduced N.toFixed, the main problem with this is the bugs in
JScripts implementation.
The other problem is that internal representation and handling with
binary numbers leads to unintuitive results that seem wrong.

toFixed calls internal ToNumber which calls internal ToInteger, to get
the exact mathematical value of the number. This is then rounded to a
value of the Number type.

This is why Mozilla will give 1.1255.toFixed(3) =1.125

javascript:alert(1.1255.toFixed(3))

javascript:alert(1.1255 ===
1.125499999999999944932937978592235594987869262695 3125)

Method toFixed is pretty much useless.

[snip]

Garrett
--
Jun 27 '08 #8
dhtml wrote:
>On Jun 19, 4:00 pm, FAQ server wrote:
[snip]
>ECMAScript Ed. 3.0 (JScript 5.5 [but buggy] and JavaScript 1.5)
introduced N.toFixed, the main problem with this is the bugs in
JScripts implementation.

The other problem is that internal representation and handling
with binary numbers leads to unintuitive results that seem wrong.
The only factor in making binary number handling non-intuitive is that
most human intuition is heavily influenced by our use habitual of
decimal numbers. Decimal numbers have exactly the same issues in reality
(the decimal representation of 1 divided by 3, for example, is going to
imprecise or impractical), it is just the issues appear in unfamiliar
locations (with unfamiliar values).
toFixed calls internal ToNumber which calls internal ToInteger,
to get the exact mathematical value of the number. This is then
rounded to a value of the Number type.
Wouldn't it be a good idea to look at the specification before making
assertions like this? The algorithm for - toFixed - does not call
ToNumber at all and it only calls ToInteger on the value that is its
argument (the "fractionDigits" value).
This is why Mozilla will give 1.1255.toFixed(3) =1.125
javascript:alert(1.1255.toFixed(3))
javascript:alert(1.1255 ===
1.125499999999999944932937978592235594987869262695 3125)
Method toFixed is pretty much useless.
You may be attributing an issue to the wrong part of the process.
Remember that a numeric literal in source code must be translated into
an internal number value that is an IEEE double precision floating point
number, and that not all values that can be represented as a precise
decimal value can also be precisely represented as an IEEE double
precision floating point number. If you code the numeric literal
"1.1255" and it is translated into the nearest available IEEE double
precision floating point number representation then that happens at the
compiling stage (or thereabouts) so you shouldn't fault - toFixed - for
correctly handling that approximate value when it acts at runtime.

Richard.

Jun 27 '08 #9
On Jun 21, 11:10 am, "Richard Cornford" <Rich...@litotes.demon.co.uk>
wrote:
dhtml wrote:
On Jun 19, 4:00 pm, FAQ server wrote:
>
toFixed calls internal ToNumber which calls internal ToInteger,
to get the exact mathematical value of the number. This is then
rounded to a value of the Number type.

Wouldn't it be a good idea to look at the specification before making
assertions like this? The algorithm for - toFixed - does not call
ToNumber at all and it only calls ToInteger on the value that is its
argument (the "fractionDigits" value).
Right.

toFixed calls ToInteger, which calls ToNumber.
Richard.
Jun 27 '08 #10
yukabuk wrote:
You should write this...
This -- what? --<http://www.jibbering.com/faq/#FAQ2_3>
var numberObj = new Number(6.57634);
There is no point in creating a Number object there, ...
var formattedNumber = numberObj.toFixed(2);
.... as it is created here implicitly.

var formattedNumber = (6.57634).toFixed(2);

or, parametrized:

var numberValue = 6.57634;
var formattedNumber = numberValue.toFixed(2);

However, you have missed this:

| ECMAScript Ed. 3.0 (JScript 5.5 [but buggy] and JavaScript 1.5)
| introduced N.toFixed, the main problem with this is the bugs in
| JScripts implementation.
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8*******************@news.demon.co.uk>
Jun 27 '08 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Brent Bortnick | last post by:
Does anyone know how to find out the number of decimal places a number has. I need this info so that i can round to 3 decimal places if the number has 3 decimal places or to 2 decimal places if...
1
by: Gizmo | last post by:
Hi there i was wondering if any one new to a function that rounds up a float to so many decimal places. I have a number in bytes and converting it to mb's and gb's but once its converted i need to...
3
by: Gospill | last post by:
Hi Guru, If I have string like "0D76" for example, it is actually a 0x0D76 in hex format. How can I convert the hex string 0D76 into decimal value ? So that I will get decimal value 3446 ...
4
by: STom | last post by:
How do you convert a string in C# to decimal? STom
3
by: Sandy | last post by:
Hello I need to have a value display in a label with two decimal places; e.g. "4" to display as "4.00 Any help will be appreciated Sandy
2
by: Andy | last post by:
Hi I'm really stuck outputting a double number to the console with three decimal places if the furthest right value is a zero. I can coutput the number 4.546 as 4.546 but then if I output...
1
by: jesmi | last post by:
hi!! i want to place two fix decimal places after a digit even if there is no decimal places after a digit. for example if there is a number 5, i want output 5.00 like that. please help me. ...
1
by: Serenityquinn15 | last post by:
Hi! I have a little trouble about in truncating numbers. What i want to do is to get the two decimal places. here's the example: when i try to get the half of 20500.39 it shows like...
1
by: AnandhaMurugan | last post by:
I got a numberformatException when i convert from string to decimal how to resolve it java.lang.NumberFormatException at java.math.BigDecimal.<init>(BigDecimal.java:455) at...
9
by: korea saeed | last post by:
how can i convert number string to number?(without using parsint)
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.