473,657 Members | 2,415 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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*10 0)/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.javas cript 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 1850
FAQ server wrote on 20 jun 2008 in comp.lang.javas cript:
-----------------------------------------------------------------------
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.javas cript:
You should write this...

var numberObj = new Number(6.57634) ;
var formattedNumber = numberObj.toFix ed(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.javas cript message <Xn************ ********@194.10 9.133.242>
, Fri, 20 Jun 2008 13:26:35, Evertjan. <ex************ **@interxnl.net >
posted:
>FAQ server wrote on 20 jun 2008 in comp.lang.javas cript:
>-----------------------------------------------------------------------
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.demo n.co.uk/js-round.htm#TRPFa nd press the
button.
>function round(n,d){
n = Math.floor(n*Ma th.pow(10,d)+.5 );
if (d<1) return n;
var s = Math.abs(n).toS tring();
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.demo n.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demo n.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.javas cript:
>>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.demo n.co.uk/js-round.htm#TRPFa nd 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.net wrote:
Dr J R Stockton wrote on 20 jun 2008 in comp.lang.javas cript:
>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.""""""""@ph ysics.org or (better) via Home Page at
Web: <URL:http://www.merlyn.demo n.co.uk/>
FAQish topics, acronyms, links, etc.; Date, Delphi, JavaScript, ...

Jun 27 '08 #7
On Jun 19, 4:00*pm, "FAQ server" <javascr...@dot internet.bewrot e:

[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:aler t(1.1255.toFixe d(3))

javascript:aler t(1.1255 ===
1.1254999999999 999449329379785 922355949878692 626953125)

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:aler t(1.1255.toFixe d(3))
javascript:aler t(1.1255 ===
1.1254999999999 999449329379785 922355949878692 626953125)
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...@litote s.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

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

Similar topics

3
7077
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 the number has 2 decimal places. Any help would be great. Regards, Brent
1
11658
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 be able to do it to 2 decimal places. Thanks for any help Scott.
3
122071
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 Thanks.
4
78776
by: STom | last post by:
How do you convert a string in C# to decimal? STom
3
28907
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
2765
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 0.220 it comes out as 0.22 and drops the zero. Also, outputting 1.000 outputs as 1. How can I format it to include the zeros?
1
2572
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. thanks in advance
1
2640
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 this:10250.195 but what i want to see is 10250.19 only. another one is 20500.42, it shows like this: 10250.2 which in real, it must be 10250.21.
1
3351
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 java.math.BigDecimal.<init>(BigDecimal.java:724) at org.openbravo.erpCommon.ad_reports.Hierarchical_trial_balance_report.printPagePDF(Hierarchical_trial_balance_report.java:550) at...
9
3889
by: korea saeed | last post by:
how can i convert number string to number?(without using parsint)
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8842
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8513
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8617
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6176
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2742
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.