473,387 Members | 1,942 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,387 software developers and data experts.

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

-----------------------------------------------------------------------
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 the section on "simple decimal arithmetic"
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 ` Number.prototype.toFixed `, the main problem
with this is the bugs in JScript's implementation.

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

function Stretch(Q, L, c) { var S = Q
if (c.length 0) {
while (S.length < L) {
S = c+S;
}
}
return S;
}

function StrU(X, M, N) { // X>=0.0
var T, S = String(Math.round(X * Number("1e" + N)));
if (S.search && S.search(/\D/) != -1) {
return '' + X;
}
with (String(Stretch(S, M+N, '0')))
return substring(0, T = (length-N)) + '.' + substring(T);
}

function Sign(X) {
return X 0 ? "+" : X < 0 ? "-" : " ";
}

function StrS(X, M, N) {
return Sign(X) + StrU(Math.abs(X), M, N);
}

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.

Oct 29 '08 #1
2 3063
In comp.lang.javascript message <49***********************@news.sunsite.
dk>, Wed, 29 Oct 2008 00:00:02, FAQ server <ja********@dotinternet.be>
posted:

And did so in a very timely manner, the topic having been raised in the
"JavaScript Math vs Excel" thread.
>FAQ Topic - How do I convert a Number into a String with
exactly 2 decimal places?
...
>http://www.merlyn.demon.co.uk/js-round.htm
To that line should be appended an indication that the logically-
following pages should also be read; my current StrU is in the next.
I'd just append either " ff." or " /ff./", expecting readers to
understand it. YMMV.

The functions are the FAQ are NOT what I presently use. My present
ones, StrU ff. at <URL:http://www.merlyn.demon.co.uk/js-rndg1.htm#GC>
give the called-for not-too-big numeric fixed-point decimal result when
possible, and otherwise indicate exactly what the input value was,
including both Infinities, NaN, null, undefined - and with the correct
number of spaces, if necessary (the string may be too long, but not too
short). I was about to assert that they thereby cover all
possibilities, when I realised that there was one omission - and that I
could easily fix it.

I'll let you all think about it for a bit ...

--
(c) John Stockton, near London. *@merlyn.demon.co.uk/?.**********@physics.org
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.
Correct <= 4-line sig. separator as above, a line precisely "-- " (SoRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "" (SoRFC1036)
Oct 29 '08 #2
In comp.lang.javascript message <QE**************@invalid.uk.co.demon.me
rlyn.invalid>, Wed, 29 Oct 2008 20:13:12, Dr J R Stockton
<jr*@merlyn.demon.co.ukposted:
>>FAQ Topic - How do I convert a Number into a String with
exactly 2 decimal places?
>The functions are the FAQ are NOT what I presently use. My present
ones, StrU ff. at <URL:http://www.merlyn.demon.co.uk/js-rndg1.htm#GC>
...
I was about to assert that they thereby cover all
possibilities, when I realised that there was one omission - and that I
could easily fix it.

I'll let you all think about it for a bit ...
Over two days have elapsed. Neither the routines in the FAQ, nor any
others that I had seen (my own included) up to Wednesday evening, can
represent the difference between +0 and -0.

The present FAQ routines give a leading space for +0 and -0, and an
appropriate sign for all other numbers, including infinities and those
which round to zero.

To get a signed zero, replace function Sign with
function Sygn(X) { return X + 1/X 0 ? "+" : "-" }

So, in the FAQ, keep Sign (being more commonly wanted?), but give Sygn
as well.

The FAQ routines survive missing arguments. They also survive the first
argument being a Function, Array, or Object. I have been wondering
whether what they then do can be improved without adding too much code.

The FAQ is now visible at the URL in FAQ 9.91 :-) .

--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk BP7, Delphi 3 & 2006.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.bancoems.com/CompLangPascalDelphiMisc-MiniFAQ.htmclpdmFAQ;
NOT <URL:http://support.codegear.com/newsgroups/>: news:borland.* Guidelines
Nov 1 '08 #3

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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...

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.