471,896 Members | 1,720 Online

# Decimall Float Question

hey,

I have float values that look something like this when they are
printed:
6.0E-4
7.0E-4

I don't want them to be like this I want them to be normalized with 4
decimal places.

If anybody can show me how to do this it would be greatly appreciated.
-morc

Apr 4 '06 #1
19 4540 // Roundoff routine for 4 decimal places
// used someplaces.

function round(x) {
return Math.round(x*10000)/10000;
}

Apr 4 '06 #2
thanks
but can somebody guide me on how to do this with BidDecimal.
I've been looking through the documentation and I can't figure it out.

Apr 4 '06 #3
"morc" <qu*************@msn.com> writes:
I have float values that look something like this when they are
printed:
6.0E-4
7.0E-4

I don't want them to be like this I want them to be normalized with 4
decimal places.

If you want to control the representation, you will need to construct
the strings yourself.

One suggestion:
function roundToString(n, decCount) {
var intpart = ((decCount == 0) ? Math.round : Math.floor)(n);
var res = String(intpart);
if (decCount > 0) {
var fracPart = n - intpart;
var offset = Math.pow(10,decCount);
var string = String(Math.round((1 + fracPart)*offset));
res += "."+string.substring(1);
}
return res;
}

It has its limits as well, since it uses Javascript's internal
number-to-string operation at places, but for reasonable sizes
(e.g. 0-10 digits on each site of the decimal points) it should
work.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Apr 4 '06 #4
oh geez... i did not realise i was posting in a javascipt group.
I'm sorry this isn't a java script problem please ignore this post.

Apr 4 '06 #5
JRS: In article <bq**********@hotpop.com>, dated Tue, 4 Apr 2006
19:12:22 remote, seen in news:comp.lang.javascript, Lasse Reichstein
Nielsen <lr*@hotpop.com> posted :

One suggestion:
function roundToString(n, decCount) {
var intpart = ((decCount == 0) ? Math.round : Math.floor)(n);
var res = String(intpart);
if (decCount > 0) {
var fracPart = n - intpart;
var offset = Math.pow(10,decCount);
var string = String(Math.round((1 + fracPart)*offset));
res += "."+string.substring(1);
}
return res;
}

It has its limits as well, since it uses Javascript's internal
number-to-string operation at places, but for reasonable sizes
(e.g. 0-10 digits on each site of the decimal points) it should
work.

Not for negative numbers (try on (0.0 - RoundingError)); could be made
to fail better for large positive ones, NaN, infinity, undefined.

The OP should have read the newsgroup FAQ; see below. Section 4.6
treats the topic and has links.

The rounding of exactly-representable half-way cases may need
consideration.

<FAQENTRY> Rename 4.6 to remove the "2", since the article is more
general. </FAQENTRY>

ISTM that fracPart = n % 1

I don't think I have a method using 1+fracpart .. substring(1) in js-
round.htm at present.

--
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
Apr 4 '06 #6
el*********@electrician.com said on 05/04/2006 2:45 AM AEST:
// Roundoff routine for 4 decimal places
// used someplaces.

function round(x) {
return Math.round(x*10000)/10000;
}

round(123.1239499999999); // gives 123.1239

but:

round(123.12394999999999); // gives 123.124
Do you know why your function does that?
--
Rob
Group FAQ: <URL:http://www.jibbering.com/FAQ>
Apr 5 '06 #7
JRS: In article <bq**********@hotpop.com>, dated Tue, 4 Apr 2006
19:12:22 remote, seen in news:comp.lang.javascript, Lasse Reichstein
Nielsen <lr*@hotpop.com> posted :
function roundToString(n, decCount) {
var intpart = ((decCount == 0) ? Math.round : Math.floor)(n);
var res = String(intpart);
if (decCount > 0) {
var fracPart = n - intpart;
var offset = Math.pow(10,decCount);
var string = String(Math.round((1 + fracPart)*offset));
res += "."+string.substring(1);
}
return res;
}

roundToString(1.994, 2) 1.99
roundToString(1.996, 2) 1.00

--
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
I find MiniTrue useful for viewing/searching/altering files, at a DOS prompt;
free, DOS/Win/UNIX, <URL:http://www.idiotsdelight.net/minitrue/>
Apr 6 '06 #8
Dr John Stockton <jr*@merlyn.demon.co.uk> writes:
roundToString(1.994, 2) 1.99
roundToString(1.996, 2) 1.00

Whoops. Just ignore that an I'll try again. :)

function roundToString(number, positions) {
var e = Math.pow(10,positions);
var s = String(Math.round(number*e));
var offset = s.length - positions;
return s.substring(0,offset) + "." + s.substring(offset);
}

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Apr 6 '06 #9
Lasse Reichstein Nielsen said on 07/04/2006 6:46 AM AEST:
Dr John Stockton <jr*@merlyn.demon.co.uk> writes:

roundToString(1.994, 2) 1.99
roundToString(1.996, 2) 1.00

Whoops. Just ignore that an I'll try again. :)

function roundToString(number, positions) {
var e = Math.pow(10,positions);
var s = String(Math.round(number*e));
var offset = s.length - positions;
return s.substring(0,offset) + "." + s.substring(offset);
}

/L

That still has issues, e.g.:

roundToString(1.015, 2) 1.01
roundToString(1.025, 2) 1.02
roundToString(1.035, 2) 1.03
roundToString(1.045, 2) 1.05
roundToString(1.055, 2) 1.06
It seems to me that the only way to properly round numbers is to treat
them as a string and round as a human would: to round to n places, look
at the n+1 digit and round right-to-left from there.

The use of Numbers and any kind of decimal arithmetic introduces inaccuracy.
--
Rob
Group FAQ: <URL:http://www.jibbering.com/FAQ>
Apr 6 '06 #10
> Decimall Float Question

Actually this question was explored in our recent thread (but with a
stress on BigInt). btw recently it is the most popular info on the
subject in application to JavaScript, reproduced in many places. Try
google "JavaScript BigMath" -> "I'm feeling lucky".

That is always the question of *really needed* precision. Say you can
take PI as 3.14 or with 32 signs. For example in the electric industry
many low-level elements have very beefy margins. Say resistors usually
have +/- 10% fluctuations from the declared resistance. In such case
overly precise calculations would be pointless. (Though a serious
calculator should have a bottom disclosure for average/max error per
calculation and average/max cummulative error for multiple
calculations).

But I see dangerous to try to find a quick-short-yet-universal solution
for BigMath: either for BigInt or BigFloat. It is a very complicated
mathematical and technical task and it requires much more then a couple
of lines to squeeze into some FAQ.

Besides the mentioned BigInt library at
<http://www.leemon.com/crypto/BigInt.html>, one could find interesting
in BigFloat libraries from IBM (free for personal use) with any given
precision level up to machine memory limit. There is no JavaScript
there unfortunately, but there is one Java implementation which is
maybe possible to port (or maybe not):

<http://www-128.ibm.com/developerworks/library/l-mathlibs/index.html>

Apr 7 '06 #11
VK wrote:
Decimall Float Question [...]
That is always the question of *really needed* precision.
I would think that rounding is almost always done on the client to display
numbers to the user. There should be a consistent, reliable and simple
algorithm to round to 2 decimal places that *always* works. Even the one
posted in the FAQ does not meet that criterion.

I agree with Hal that the code posted there is not aimed at teaching
newbies, nor does it fit the criteria posted above. The technical
explanations are OK, they need to be brief. The posted code is
unnecessarily concise and difficult to understand - senior posters here
have stated that 'with' should not be used for just that reason, yet it is
included in code posted on the FAQ. It's use doesn't seem justified other
than to save a few key strokes for whoever wrote it.

If rigorous solution requires more code, then so be it - at least make it
available. Let visitors decide if they wish to use a longer, rigorous
solution or more concise, sometimes wrong one.

*All* of the algorithms posted at www.merlyn* use Math functions and
multiplication which must inherently introduce errors. Why is there not a
single example of a rounding function that works always?

... Say you can
take PI as 3.14 or with 32 signs. For example in the electric industry
many low-level elements have very beefy margins. Say resistors usually
have +/- 10% fluctuations from the declared resistance. In such case
overly precise calculations would be pointless. (Though a serious
calculator should have a bottom disclosure for average/max error per
calculation and average/max cummulative error for multiple
calculations).
Once upon a time I was a practicing surveyor, I understand the theory of
errors and error propagation. But that has nothing to do with rounding,
which should generally be done once and once only - at the very end.

Sometimes rounding is done in manual calculations for convenience, I thing
it would only be used in a computer program for the same reason.

But I see dangerous to try to find a quick-short-yet-universal solution

for BigMath: either for BigInt or BigFloat.

I'm not asking for that at all, just a rounding function that works.

[...] mathematical and technical task and it requires much more then a couple
of lines to squeeze into some FAQ.
There are numerous pages at www.merlyn, put it there and link to it. The
current function in the FAQ is 15 of nearly useless, obfuscated code,
replace that. Statements like:

"Much code for trailing zeros fails for some numbers (e.g. 0.07)."

Besides the mentioned BigInt library at
<http://www.leemon.com/crypto/BigInt.html>, one could find interesting
in BigFloat libraries from IBM (free for personal use) with any given
precision level up to machine memory limit. There is no JavaScript
there unfortunately, but there is one Java implementation which is
maybe possible to port (or maybe not):

I realise your advice is well intentioned, but it's not really suitable to
recommend porting some unknown component of a Java/C/C++ library to
JavaScript to answer a simple question.

--
Rob
Apr 7 '06 #12

RobG wrote:
it it's not really suitable to
recommend porting some unknown component of a Java/C/C++ library to
JavaScript to answer a simple question.

It is not a simple question at all :-)
The major problem as I see it is that IEEE > BigFloat is not always
back-reversable. I mean it is not always possible to:

var myFloat = 1.2345;
doExactMath(myFloat);

It is possible up to some rather narrow limit to be found yet for
JavaScript. After that border it doesn't work anymore because some
non-reversable changes (rounding, digit loss) will happen at the very
moment of initialization or on the first attempt to get the value
(either in numeric or string form). So above this limit you have to
pre-declare all your BigFloat's as separate objects with string
initializer:

var myBigFloat = new BigFloat('1.2345678901234567890');
doExactMath(myBigFloat);

So first this "no return point" has to be determined - otherwise for
each possible algorythm ignoring it one can find a failure number.

Apr 7 '06 #13
VK wrote:
RobG wrote:
it it's not really suitable to
recommend porting some unknown component of a Java/C/C++ library to
JavaScript to answer a simple question.

It is not a simple question at all :-)
The major problem as I see it is that IEEE > BigFloat is not always
back-reversable. I mean it is not always possible to:

var myFloat = 1.2345;
doExactMath(myFloat);

You're missing the point. The rounding function itself should not modify
the number other than to round the decimal part. For example, the typical
round to money function of:

var x = Math.round(x*100)/100;

if given 1.025 returns 1.02, not 1.03 which is typically required (assuming
'bankers rounding' to the nearest even number is not required). That's
what I mean by the rounding function introducing errors.

The function below doesn't, try it out and see. Let me know if it breaks.
I've fully commented it, remove all that and it's two lines longer than
the example in the FAQ.
<script type="text/javascript">

/* Round numbers to two decimal places
* Always rounds .xx5 upward.
*/
function roundTwo(num)
{
// Make a string 3 characters by adding zeros
// or truncating
function str3(x) {
while (x.length < 3) {x += '0';}
return x.substring(0,3);
}
// Split number into integer and decimal bits
var bits = (num+'').split('.');

// Get the decimal part
var frac = bits || '';

// Make the number all digits with no decimal place
// as if had done num*1000 and truncated decimal places
// Split into an array of single digits
var digits = (bits + str3(frac)).split('');

// Round the second last digit up if the last digit
// is 5 or greater
var i = digits.length;
if (digits[--i] > 4) { digits[--i] = +digits[i] + 1; }

// While the last number is 10, make it a zero and
// carry 1 to left
while (i && digits[i] > 9){
digits[i] = 0;
digits[--i] = +digits[i] + 1;
}

// Make the digits a string again
digits = digits.join('');

// Put the decimal place back in and return a string
// Leave off the last digit
i = digits.length-3;
return digits.substring(0,i) + '.' + digits.substring(i, i+2);
}

</script>

<input type="text" size="100" onkeyup="
document.getElementById('xx').innerHTML = roundTwo(this.value);
">
<div id="xx"></div>

--
Rob
Apr 7 '06 #14
JRS: In article <3b**********@hotpop.com>, dated Thu, 6 Apr 2006
22:46:27 remote, seen in news:comp.lang.javascript, Lasse Reichstein
Nielsen <lr*@hotpop.com> posted :
Dr John Stockton <jr*@merlyn.demon.co.uk> writes:
roundToString(1.994, 2) 1.99
roundToString(1.996, 2) 1.00

Whoops. Just ignore that an I'll try again. :)

function roundToString(number, positions) {
var e = Math.pow(10,positions);
var s = String(Math.round(number*e));
var offset = s.length - positions;
return s.substring(0,offset) + "." + s.substring(offset);
}

roundToString(+0.07, 2) .7 // !!
roundToString(-0.07, 2) .-7 // !!
roundToString(0, 2) .0 // ***
roundToString(1e20, 2) 1e+.22

*** Use of a decimal point without a digit on each side is deprecated in
international scientific circles. ISTM that it's reasonable for a
routine to be capable of giving that, provided that it is, for every
value of the generally-varying parameter, capable of *not* giving that.

I think you arrived here in c.l.j after the discussion which led to the
present contents of FAQ 4.6; previously, IIRC, it had something rather

Any such function, if it may be used with an argument which is nominally
zero but has been calculated by non-integer arithmetic, needs to be
tested with small negative values :

0.06 - (0.01+0.05) gives -6.938893903907228e-18
~~

I don't much like a value for e which is not 2.718...

--
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
Apr 7 '06 #15
01.iinet.net.au>, dated Fri, 7 Apr 2006 19:39:58 remote, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.au> posted :

*All* of the algorithms posted at www.merlyn* use Math functions and
multiplication which must inherently introduce errors.
Well, I don't see a multiplication in <URL:http://www.merlyn.demon.co.uk
/js-misc0.htm#CNTES> :
function CentNoToEuroStr(C) { // C>=0
var S = String(Math.round(C)), Euro = "\u20AC"
while (S.length<3) S = "0" + S
return Euro + S.replace(/(\d\d)\$/, ".\$1") }

BTW, something like the last line could perhaps be used in your code;
Why is there not a
single example of a rounding function that works always?

Because circumstances vary too much to make a single function
appropriate, unless several distinct pieces of code are packed in a
single function and a parameter is used to choose one of them.

Or, historically, because the Originators of Javascript were not
intelligent enough to specify an adequate set of conversion methods for
type Number to String. Earlier language implementations - Fortran,
Algol, Pascal and probably others - did better.

--
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
Apr 7 '06 #16
01.iinet.net.au>, dated Fri, 7 Apr 2006 23:41:13 remote, seen in
news:comp.lang.javascript, RobG <rg***@iinet.net.au> posted :
The rounding function itself should not modify
the number other than to round the decimal part. For example, the typical
round to money function of:

var x = Math.round(x*100)/100;

if given 1.025 returns 1.02, not 1.03 which is typically required (assuming
'bankers rounding' to the nearest even number is not required). That's
what I mean by the rounding function introducing errors.
But you don't give it 1.025. You give it a variable of type Number
which has been loaded by something equivalent to +"1.025" ; and, since
that three-digit decimal part is not a multiple of an eighth, the value
cannot be stored exactly. The rounding is correct.

While the user of a Web page cannot be expected to understand binary
float capabilities in detail, and the FAQ reader ought to but probably
does not (yet?), the providers of such code do need to know exactly what
is happening arithmetically.
Where the input Number is obtained by a physical calculation, general
convention is that an exact half rounds away from zero and that anything
not exactly a half rounds to nearest. Uncertainties mean that for
numbers near a half, rounding either way gives an almost equally good
result.

But when the input Number is obtained by an administrative calculation,
an exact half should round as required by the application and a very-
close-to-half should round as if it were exactly half.

In a sufficiently large administrative calculation, accumulated rounding
error may mean that num+"" does not have the right digit to the right
of the chopping-point. It might help to round to more digits, then
round to fewer.
<FAQENTRY>
On the other hand, if one wants exact results one should be doing an
integer calculation anyway; cents, not dollars - or, as in the Delphi
(IEEE?) Currency type, centicents.
</FAQENTRY>

The function below doesn't, try it out and see. Let me know if it breaks.
I've fully commented it, remove all that and it's two lines longer than
the example in the FAQ.
However, the FAQ code includes having a variable number of digits after
the decimal point and a variable (but at least as many as are necessary)
number before it, and has code added to ensure a benign result for
numbers too large for the basic algorithm.

/* Round numbers to two decimal places
* Always rounds .xx5 upward.
Towards plus infinity or away from zero? They are not equivalent for
num<0. Comment needs to say whether num<0 is allowed; and it must be
said that a nominal 0.0 may actually be negative.
// Make a string 3 characters by adding zeros
// or truncating
function str3(x) {
while (x.length < 3) {x += '0';}
return x.substring(0,3);
or return (x+"000").substring(0, 3) ??

}
// Split number into integer and decimal bits
integer and fractional ?
var bits = (num+'').split('.');
Comment : // Convert number to string and split ...
// Get the decimal part
fractional ?
var frac = bits || '';

// Make the number all digits with no decimal place
// as if had done num*1000 and truncated decimal places
// Split into an array of single digits
var digits = (bits + str3(frac)).split('');

// Round the second last digit up if the last digit
// is 5 or greater
var i = digits.length;
if (digits[--i] > 4) { digits[--i] = +digits[i] + 1; }

// While the last number is 10, make it a zero and
// While the last digit ... ?
// carry 1 to left
while (i && digits[i] > 9){
digits[i] = 0;
digits[--i] = +digits[i] + 1;
}

// Make the digits a string again
digits = digits.join('');

// Put the decimal place back in and return a string point
// Leave off the last digit
i = digits.length-3;
return digits.substring(0,i) + '.' + digits.substring(i, i+2);
}

</script>

However, roundTwo(+99.9999) gives 100.00 but roundTwo(-99.9999) gives me
NaN00.00 ; presumably because the first character is not a number.

IMHO, however, negative numbers should be done with Math.abs and finally
and -£3.33; and has the great benefit of reducing the amount of testing
needed.
Another approach, like that done for Bankers' Rounding in js-misc0.htm,
is to convert to String and look at the MSD of the part to be chopped.
If that's 0 to 4, chop. Otherwise, increment the original number by
what amounts to about 7 in that digit, and chop.

--
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
Apr 7 '06 #17

VK wrote:
one could find interesting
in BigFloat libraries from IBM (free for personal use) with any given
precision level up to machine memory limit. There is no JavaScript
there unfortunately, but there is one Java implementation which is
maybe possible to port (or maybe not):

<http://www-128.ibm.com/developerworks/library/l-mathlibs/index.html>

I guess it is already done:
<http://stz-ida.de/html/oss/js_bigdecimal.html.en>

Apr 8 '06 #18
RobG <rg***@iinet.net.au> writes:
Lasse Reichstein Nielsen said on 07/04/2006 6:46 AM AEST:
Whoops. Just ignore that an I'll try again. :)
That still has issues, e.g.:

roundToString(1.015, 2) 1.01
roundToString(1.025, 2) 1.02
Indeed. It works "correctly" when looking at the number, because
the number you get from 1.025 is actually not exactly 1.025, but
a little less. So, we need to take the Javascript number and guess
its intended value.
It seems to me that the only way to properly round numbers is to treat
them as a string and round as a human would: to round to n places,
look at the n+1 digit and round right-to-left from there.
Let's try that.

function roundToString(number, pos) {
var s = String(number); // only works if not exponential presentation
var i = s.indexOf(".");
if (s.length <= i+pos+1) {
return s;
}
var intpart = s.substring(0,i)+s.substring(i+1,i+1+pos)+"."+s.ch arAt(i+pos+1);
var rs = String(Math.round(Number(intpart)));
return rs.substring(0,rs.length-pos) + "."
+ rs.substring(rs.length-pos);
}
The use of Numbers and any kind of decimal arithmetic introduces inaccuracy.

Actually, multiplying by 100 does not introduce inaccuracy. The result
is exactly 100 times the original number. It's just that the original number
vas not exactly what was typed as the literal.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Apr 8 '06 #19
JRS: In article <64**********@hotpop.com>, dated Sat, 8 Apr 2006
12:29:25 remote, seen in news:comp.lang.javascript, Lasse Reichstein
Nielsen <lr*@hotpop.com> posted :

Actually, multiplying by 100 does not introduce inaccuracy. The result
is exactly 100 times the original number.

Not necessarily. The multiplier 100 itself is stored accurately, in an
IEEE Double as binary 1100100 with complications.

Multiplication by 64 = 1000000 would be done by just incrementing the
exponent.

But if the multiplicand, in a Double, has non-zero bits among the lowest
4 positions, then there is nowhere to put the product of those bits with
the lower bits of 100. However, the use of guard bits within the FPU
ensures, I think, that the result will be the ideal result properly
rounded to the number of bits stored.
However it is better to multiply or divide by 100 than to divide or
multiply by 0.01 since 0.01 itself cannot be stored exactly. Except
that sometimes the error contributions have opposite signs.

<FAQENTRY>
The word "span" should be "spam".
posts in other groups or in mail.
</FAQENTRY>

FORTRAN has a built-in convention that by default identifiers beginning
with I J K L M N represent integers and the others represent floats.
Javascript rightly has no such fixed convention.

However, ISTM on the whole useful to follow that convention in
javascript, where convenient - in other words, in a piece of code with
the usual mix of integer and float, to prefer to name variables in that
fashion especially when they don't hold values for many lines and are
going to be given short names anyway.

Context, of course, usually helps to indicate whether a variable is or
is not being used for a Number.

--
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
 5 posts views Thread by Code4u | last post: by 15 posts views Thread by Kay Schluehr | last post: by 6 posts views Thread by Martin Bootsma | last post: by 3 posts views Thread by hantechs | last post: by 4 posts views Thread by JoeC | last post: by 9 posts views Thread by gdarian216 | last post: by 12 posts views Thread by kostas | last post: by 22 posts views Thread by Bill Reid | last post: by reply views Thread by Timothy Grant | last post: by reply views Thread by antdb | last post: by reply views Thread by YellowAndGreen | last post: by 1 post views Thread by isladogs | last post: by reply views Thread by beacampos | last post: by reply views Thread by zermasroor | last post: by 6 posts views Thread by Sullster47 | last post: by reply views Thread by beacampos | last post: by reply views Thread by Temur2 | last post: by reply views Thread by slayersays | last post: by