Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. What's y'all's favorite way of dealing with floating point precision?

What's y'all's favorite way of dealing with floating point precision?

Scheduled Pinned Locked Moved The Lounge
questionjavascriptcareer
67 Posts 25 Posters 11 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Jeremy Falcon

    Yeah, but to be fair... this issue is with all languages. Edit: Unless you mean the decimal type in C#? In which case... totally gotta give props to that.

    Jeremy Falcon

    M Offline
    M Offline
    Marc Clifton
    wrote on last edited by
    #32

    Yes exactly, the decimal type in C#. I was going to mention it but it seemed like the context of your question was JavaScript. ;) And for SQL, there's a really interesting post here[^] about how to use the money and decimal types correctly. Learned something looking that up!

    Latest Articles:
    A Lightweight Thread Safe In-Memory Keyed Generic Cache Collection Service A Dynamic Where Implementation for Entity Framework

    1 Reply Last reply
    0
    • D Daniel Pfeffer

      This is why COBOL has a decimal type. Your approach of using integers to represent currency will work, subject to a few caveats: 1. Accounting rules require that calculations (e.g. multiplication, division) be performed with greater than 1 cent accuracy (5 decimal places, IIRC). This allows interest calculations, currency conversions etc. to work properly. 2. Rounding is performed using accounting rules - round to nearest or AWAY. The difference between this and round to nearest or EVEN is when the fraction is exactly 0.5. If this case, one rounds AWAY from 0. For example, 3.145 would round to nearest or EVEN as 3.14, but round to nearest or AWAY as 3.15. There may be other rules for accounting, but these are the major ones.

      Freedom is the freedom to say that two plus two make four. If that is granted, all else follows. -- 6079 Smith W.

      J Offline
      J Offline
      jmaida
      wrote on last edited by
      #33

      I remember COBOL. I worked for an accountant/programmer during grad school. His clients used NCR COBOL machines with COBOL interpreter language. Bullet proof.

      "A little time, a little trouble, your better day" Badfinger

      1 Reply Last reply
      0
      • D Daniel Pfeffer

        Amarnath S wrote:

        we had DOUBLE PRECISION in Fortran and double in C.

        Even with binary DOUBLE PRECISION, you would get errors in accounting formulas. This is why COBOL was specified to have a decimal type.

        Freedom is the freedom to say that two plus two make four. If that is granted, all else follows. -- 6079 Smith W.

        J Offline
        J Offline
        jmaida
        wrote on last edited by
        #34

        Yes sir. :)

        "A little time, a little trouble, your better day" Badfinger

        1 Reply Last reply
        0
        • D Daniel Pfeffer

          This is why COBOL has a decimal type. Your approach of using integers to represent currency will work, subject to a few caveats: 1. Accounting rules require that calculations (e.g. multiplication, division) be performed with greater than 1 cent accuracy (5 decimal places, IIRC). This allows interest calculations, currency conversions etc. to work properly. 2. Rounding is performed using accounting rules - round to nearest or AWAY. The difference between this and round to nearest or EVEN is when the fraction is exactly 0.5. If this case, one rounds AWAY from 0. For example, 3.145 would round to nearest or EVEN as 3.14, but round to nearest or AWAY as 3.15. There may be other rules for accounting, but these are the major ones.

          Freedom is the freedom to say that two plus two make four. If that is granted, all else follows. -- 6079 Smith W.

          J Offline
          J Offline
          jschell
          wrote on last edited by
          #35

          Daniel Pfeffer wrote:

          There may be other rules for accounting

          In certain domain spaces there are regulations that must be followed. And they can vary by political region.

          1 Reply Last reply
          0
          • G Gary Wheeler

            Okay, I'm now having flashbacks to my numerical methods class in college. One of the central points in the course was that managing precision was important, but it had to be appropriate to the calculation. You've hit on that with currency. I remember a story where a programmer at a bank embezzled a lot of money based on harvesting roundoff error in the bank's software that he wrote. There are certifications and legal mechanisms that define how calculations are performed now. Scientific computation is similar. It's hard to imagine the analysis that the Large Hadron Collider experiments require, since the data of interest is embedded in unbelievable amounts of noise. Heck, it's even a problem in my world of commercial ink-jet printing systems. Our internal unit of measurement is µinches (micro-inches) in a 64-bit signed integer. We deal with positioning data in 1/3600ths of an inch that can be noisy, and our resolution is 600 dots/inch. Using µinches solves a lot of scaling issues.

            Software Zen: delete this;

            M Offline
            M Offline
            Mark_Whybird
            wrote on last edited by
            #36

            This is the only correct answer: it has to be appropriate to the calculation. In some cases, perfect precision is not even mathematically possible (e.g. pi = ratio of a circle's diameter to circumference, or anything involving it like sin() or cos()). Rational libraries are great when appropriate, but (a) they can be a lot of computing for no real world benefit, and (b) if you have any intrinsically irrational number like pi in there anywhere, their usefulness instantly becomes limited (or you have to factor out the irrationals and express the answers as ratios of them...) So, yeah, in real life, calculate at higher than needed* precision and round to needed precision. For accounting, use appropriate accounting rounding rules for exact 0.5 values. *what precision? Max total of your errors all added and multiplied together appropriately according to the calculations involved must be less than half of the actual final precision.

            1 Reply Last reply
            0
            • J Jeremy Falcon

              Not sure if this counts as a programming question, since I'm not asking for code but rather preference. I'm in a project that requires complete accuracy on numbers. So, given the following... We all know the famous of examples of stuff like this:

              0.1 + 0.2 // 0.30000000000000004

              Up until now, I've been content with rounding off any operations after the fact and calling it a day, as close enough was good enough. For applications, say that deal with currency, the age old trick is to just use integers based on a cent value. So, a `$1.23` would be stored as `123` in a variable. Sweet, but, consider this:

              // $123.45 / $2.25
              12345 / 225 // 54.86666666666667

              If I move along powers of the base, I never run into issues. But for your typical run of the mill calculations, even with integers, you still have to deal with fractional floating points in the arithmetic. So, I've been using integers _and_ rounding off any calculations to their nearest integer value. Maybe sometimes I'll `floor` or `ceil` depending on context, but that's been my current solution, which is a lot more accurate but not 100% accurate. But, good enough-ish. Soooo.... 1) You guys prefer using a library to handle stuff like this? IMO I don't use one for arithmetic because most libraries for this (at least in JavaScript) are clunky and slow and don't really do a better job anyway. 2) You think integers and rounding is also the way to go? Keeps crap simple and all that, despite needing to remember to always round after division calculations or calculations against fractional types. 3) Never do arithmetic? Tell the user to go home.

              Jeremy Falcon

              D Offline
              D Offline
              den2k88
              wrote on last edited by
              #37

              I work in engineering applications so my answer is "I don't use floating point arithmetic", everything is fixed point - many microcontrollers do not have an FPU at all and what I do is mostly real-time so forget software emulation. Any desktop tool has to provide or receive data from these systems so it's mostly fixed point until it's time to show to the user. On non engineering applications I just use floating points as they are, if I have qualms about precision I just use double or long double and call it a day - I don't work on servers or high throughput / low latency services so I just don't care.

              GCS/GE d--(d) s-/+ a C+++ U+++ P-- L+@ E-- W+++ N+ o+ K- w+++ O? M-- V? PS+ PE Y+ PGP t+ 5? X R+++ tv-- b+(+++) DI+++ D++ G e++ h--- r+++ y+++*      Weapons extension: ma- k++ F+2 X The shortest horror story: On Error Resume Next

              1 Reply Last reply
              0
              • J Jeremy Falcon

                I was waiting for that. Had to give COBOL some love though.

                Jeremy Falcon

                J Offline
                J Offline
                Jorgen Andersson
                wrote on last edited by
                #38

                Jeremy Falcon wrote:

                Had to give COBOL some love though.

                Rightfully so, COBOL is better than its reputation. And still in development, latest version is COBOL-2023.

                Wrong is evil and must be defeated. - Jeff Ello

                1 Reply Last reply
                0
                • J Jeremy Falcon

                  Sometimes I do wish JavaScript had better types like that. I can push a precision to about 9 or 10 in JavaScript before the storable value becomes too small to be worth while. Good enough for kiddie stuff at least. But yeah, also what Daniel said. :laugh:

                  Jeremy Falcon

                  B Offline
                  B Offline
                  bjongejan
                  wrote on last edited by
                  #39

                  Javascript's innate number type is but an approximation - everybody will agree. But the serialization of those numbers in JSON makes it worse. For example, what is really meant with 0.67, 0.667, ... , 0.66666666666667 ? Does 0.67 mean exactly 67 cents and is 0.66666666666667 to be understood as an approximation of 2/3? And does 0.667 also stand for 2/3? What does the number of decimals tell about the underlying intentions? JSON should have a standardized notation for lossless serialization of floating point type numbers. Even C has that: the %a printf format for double in hexadecimal notation. And talking about shortcomings in JSON: please also provide a notation for bignums - both integer and rational ones.

                  1 Reply Last reply
                  0
                  • J Jeremy Falcon

                    Not sure if this counts as a programming question, since I'm not asking for code but rather preference. I'm in a project that requires complete accuracy on numbers. So, given the following... We all know the famous of examples of stuff like this:

                    0.1 + 0.2 // 0.30000000000000004

                    Up until now, I've been content with rounding off any operations after the fact and calling it a day, as close enough was good enough. For applications, say that deal with currency, the age old trick is to just use integers based on a cent value. So, a `$1.23` would be stored as `123` in a variable. Sweet, but, consider this:

                    // $123.45 / $2.25
                    12345 / 225 // 54.86666666666667

                    If I move along powers of the base, I never run into issues. But for your typical run of the mill calculations, even with integers, you still have to deal with fractional floating points in the arithmetic. So, I've been using integers _and_ rounding off any calculations to their nearest integer value. Maybe sometimes I'll `floor` or `ceil` depending on context, but that's been my current solution, which is a lot more accurate but not 100% accurate. But, good enough-ish. Soooo.... 1) You guys prefer using a library to handle stuff like this? IMO I don't use one for arithmetic because most libraries for this (at least in JavaScript) are clunky and slow and don't really do a better job anyway. 2) You think integers and rounding is also the way to go? Keeps crap simple and all that, despite needing to remember to always round after division calculations or calculations against fractional types. 3) Never do arithmetic? Tell the user to go home.

                    Jeremy Falcon

                    M Offline
                    M Offline
                    Matt Bond
                    wrote on last edited by
                    #40

                    When seeking consistency, I would wrap all of that in a utility class. This way I know it's consistent and works the same everywhere. If I need something a little different, then I either overload or add a default parameter as the occasion requires. I agree that storing the numerator and denominator would be the best way to prevent most headaches. In C#, I would use a Fraction struct for this (home grown if one doesn't exist already). Only collapse the fraction to a primitive type as necessary. This also has the benefit of letting you use money with a decimal value, so you don't have to do the extra math to get the cents back. Speaking of money, you only have to store 4 decimals with money to be accurate for accounting purposes. I deal with fiduciary escrow accounts for my job, and that's all we've every used. Never had a problem being out of balance by a penny in 24 years. However, we don't do multiplication and division on the money. I don't think that would change much though as long as you kept the division and rounding to the end of the math problem.

                    Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere

                    J 1 Reply Last reply
                    0
                    • J Jeremy Falcon

                      Not sure if this counts as a programming question, since I'm not asking for code but rather preference. I'm in a project that requires complete accuracy on numbers. So, given the following... We all know the famous of examples of stuff like this:

                      0.1 + 0.2 // 0.30000000000000004

                      Up until now, I've been content with rounding off any operations after the fact and calling it a day, as close enough was good enough. For applications, say that deal with currency, the age old trick is to just use integers based on a cent value. So, a `$1.23` would be stored as `123` in a variable. Sweet, but, consider this:

                      // $123.45 / $2.25
                      12345 / 225 // 54.86666666666667

                      If I move along powers of the base, I never run into issues. But for your typical run of the mill calculations, even with integers, you still have to deal with fractional floating points in the arithmetic. So, I've been using integers _and_ rounding off any calculations to their nearest integer value. Maybe sometimes I'll `floor` or `ceil` depending on context, but that's been my current solution, which is a lot more accurate but not 100% accurate. But, good enough-ish. Soooo.... 1) You guys prefer using a library to handle stuff like this? IMO I don't use one for arithmetic because most libraries for this (at least in JavaScript) are clunky and slow and don't really do a better job anyway. 2) You think integers and rounding is also the way to go? Keeps crap simple and all that, despite needing to remember to always round after division calculations or calculations against fractional types. 3) Never do arithmetic? Tell the user to go home.

                      Jeremy Falcon

                      L Offline
                      L Offline
                      Lloyd Folden 2024
                      wrote on last edited by
                      #41

                      One thing to consider, there is a worldwide standard that most operating systems follow, IEEE 64-BIT. To me it wouldn't be unreasonable to follow that. Anyone situation that requires more would be highly specialized.

                      J 1 Reply Last reply
                      0
                      • J Jeremy Falcon

                        Not sure if this counts as a programming question, since I'm not asking for code but rather preference. I'm in a project that requires complete accuracy on numbers. So, given the following... We all know the famous of examples of stuff like this:

                        0.1 + 0.2 // 0.30000000000000004

                        Up until now, I've been content with rounding off any operations after the fact and calling it a day, as close enough was good enough. For applications, say that deal with currency, the age old trick is to just use integers based on a cent value. So, a `$1.23` would be stored as `123` in a variable. Sweet, but, consider this:

                        // $123.45 / $2.25
                        12345 / 225 // 54.86666666666667

                        If I move along powers of the base, I never run into issues. But for your typical run of the mill calculations, even with integers, you still have to deal with fractional floating points in the arithmetic. So, I've been using integers _and_ rounding off any calculations to their nearest integer value. Maybe sometimes I'll `floor` or `ceil` depending on context, but that's been my current solution, which is a lot more accurate but not 100% accurate. But, good enough-ish. Soooo.... 1) You guys prefer using a library to handle stuff like this? IMO I don't use one for arithmetic because most libraries for this (at least in JavaScript) are clunky and slow and don't really do a better job anyway. 2) You think integers and rounding is also the way to go? Keeps crap simple and all that, despite needing to remember to always round after division calculations or calculations against fractional types. 3) Never do arithmetic? Tell the user to go home.

                        Jeremy Falcon

                        B Offline
                        B Offline
                        Bruce Patin
                        wrote on last edited by
                        #42

                        Financial apps as far as I know use four decimal digits during calculations to avoid problems with only two, then round at the end.

                        J 1 Reply Last reply
                        0
                        • J Jeremy Falcon

                          Not sure if this counts as a programming question, since I'm not asking for code but rather preference. I'm in a project that requires complete accuracy on numbers. So, given the following... We all know the famous of examples of stuff like this:

                          0.1 + 0.2 // 0.30000000000000004

                          Up until now, I've been content with rounding off any operations after the fact and calling it a day, as close enough was good enough. For applications, say that deal with currency, the age old trick is to just use integers based on a cent value. So, a `$1.23` would be stored as `123` in a variable. Sweet, but, consider this:

                          // $123.45 / $2.25
                          12345 / 225 // 54.86666666666667

                          If I move along powers of the base, I never run into issues. But for your typical run of the mill calculations, even with integers, you still have to deal with fractional floating points in the arithmetic. So, I've been using integers _and_ rounding off any calculations to their nearest integer value. Maybe sometimes I'll `floor` or `ceil` depending on context, but that's been my current solution, which is a lot more accurate but not 100% accurate. But, good enough-ish. Soooo.... 1) You guys prefer using a library to handle stuff like this? IMO I don't use one for arithmetic because most libraries for this (at least in JavaScript) are clunky and slow and don't really do a better job anyway. 2) You think integers and rounding is also the way to go? Keeps crap simple and all that, despite needing to remember to always round after division calculations or calculations against fractional types. 3) Never do arithmetic? Tell the user to go home.

                          Jeremy Falcon

                          C Offline
                          C Offline
                          charlieg
                          wrote on last edited by
                          #43

                          "project that requires complete accuracy on numbers" A couple of thoughts. Is not the above requirement impossible on a binary system? By the very definition, you are going to lose precision be it float, double, double double.... how far do you want to go? For me, I work a lot in machine HMIs. Some users want metric, others want English. I've always had a requirement to allow the user to switch between units and maintaining what is displayed. For example, 1" is 25.4 mm. If I switch between metric and English, the value must be consistent. As for complete accuracy - this for me has always fallen into fixed point arithmetic to avoid rounding errors. COBOL has been mentioned. I've done COBOL - a very long time ago, but as I recall, it did fixed point arithmetic very well. Or I might be missing something... Please elaborate on what you mean for "complete accuracy"? This sounds like a requirement from someone who really does not understand their request - sort of like a rare steak, but the temp should be 175F....

                          Charlie Gilley “They who can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.” BF, 1759 Has never been more appropriate.

                          J 1 Reply Last reply
                          0
                          • J Jeremy Falcon

                            Not sure if this counts as a programming question, since I'm not asking for code but rather preference. I'm in a project that requires complete accuracy on numbers. So, given the following... We all know the famous of examples of stuff like this:

                            0.1 + 0.2 // 0.30000000000000004

                            Up until now, I've been content with rounding off any operations after the fact and calling it a day, as close enough was good enough. For applications, say that deal with currency, the age old trick is to just use integers based on a cent value. So, a `$1.23` would be stored as `123` in a variable. Sweet, but, consider this:

                            // $123.45 / $2.25
                            12345 / 225 // 54.86666666666667

                            If I move along powers of the base, I never run into issues. But for your typical run of the mill calculations, even with integers, you still have to deal with fractional floating points in the arithmetic. So, I've been using integers _and_ rounding off any calculations to their nearest integer value. Maybe sometimes I'll `floor` or `ceil` depending on context, but that's been my current solution, which is a lot more accurate but not 100% accurate. But, good enough-ish. Soooo.... 1) You guys prefer using a library to handle stuff like this? IMO I don't use one for arithmetic because most libraries for this (at least in JavaScript) are clunky and slow and don't really do a better job anyway. 2) You think integers and rounding is also the way to go? Keeps crap simple and all that, despite needing to remember to always round after division calculations or calculations against fractional types. 3) Never do arithmetic? Tell the user to go home.

                            Jeremy Falcon

                            R Offline
                            R Offline
                            realJSOP
                            wrote on last edited by
                            #44

                            you could do this:

                            decimal result = decimal(1.0) * decimal(2.0); // answer is "0.3"

                            or this:

                            double resulta = Math.Round(x + y, 5); // 5 indicates precision (answer is "0.3")

                            ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                            -----
                            You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                            -----
                            When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                            J 1 Reply Last reply
                            0
                            • J Jeremy Falcon

                              Not sure if this counts as a programming question, since I'm not asking for code but rather preference. I'm in a project that requires complete accuracy on numbers. So, given the following... We all know the famous of examples of stuff like this:

                              0.1 + 0.2 // 0.30000000000000004

                              Up until now, I've been content with rounding off any operations after the fact and calling it a day, as close enough was good enough. For applications, say that deal with currency, the age old trick is to just use integers based on a cent value. So, a `$1.23` would be stored as `123` in a variable. Sweet, but, consider this:

                              // $123.45 / $2.25
                              12345 / 225 // 54.86666666666667

                              If I move along powers of the base, I never run into issues. But for your typical run of the mill calculations, even with integers, you still have to deal with fractional floating points in the arithmetic. So, I've been using integers _and_ rounding off any calculations to their nearest integer value. Maybe sometimes I'll `floor` or `ceil` depending on context, but that's been my current solution, which is a lot more accurate but not 100% accurate. But, good enough-ish. Soooo.... 1) You guys prefer using a library to handle stuff like this? IMO I don't use one for arithmetic because most libraries for this (at least in JavaScript) are clunky and slow and don't really do a better job anyway. 2) You think integers and rounding is also the way to go? Keeps crap simple and all that, despite needing to remember to always round after division calculations or calculations against fractional types. 3) Never do arithmetic? Tell the user to go home.

                              Jeremy Falcon

                              R Offline
                              R Offline
                              rjmoses
                              wrote on last edited by
                              #45

                              It will largely depend on your application and requirements. For currency type applications, consider using a BCD (Binary Code Decimal, used in COBOL) package. See below for references. For integer type applications, there are a few "large" int packages. For scientific applications, there are a number of packages for large number processing. ************ BCD references ******************** https://web.archive.org/web/20081102170717/http://webster.cs.ucr.edu/AoA/Windows/HTML/AdvancedArithmetica6.html#1000255 https://handwiki.org/wiki/Binary-coded\_decimal#EBCDIC\_zoned\_decimal\_conversion\_table Notes: 1) BCD numbers can be packed (2 digits/byte) or unpacked (1 digit per byte) 2) The low order byte (right most) of packed is nnnnssss where nnnn is the low order digit and ssss is the sign (0x0D for negative, 0x0F for positive) 3) The spec is (www,ddd) where www is the total bytes and ddd is the digits to right of decimal point. E.g.: 5,2 is a 5 digit number with 2 digits to the right of the decimal point--"123.45" This field would require 3 bytes packed, 6 bytes unpacked. 4) From IBM: For a field or array element of length N, if the PACKEVEN keyword is not specified, the number of digits is 2N - 1; if the PACKEVEN keyword is specified, the number of digits is 2(N-1). 5) Some documentation refers to BCD as DECIMAL but others use DECIMAL to refer to floating point. ********************* For large int ******************** Microsoft SafeInt package SafeInt Class | Microsoft Learn[^] The decNumber package can handle decimal integer number of user defined precision GitHub - dnotq/decNumber: Decimal Floating Point decNumber C Library by IBM Fellow Mike Cowlishaw[^] (I have not yet used or investigate the cran project.) CRAN - Package VeryLargeIntegers[^] ******************** For Floating Point ******************** Floating point gets very complex and confusing because there has never been a really good, consistent standard

                              J 1 Reply Last reply
                              0
                              • J Jeremy Falcon

                                There is a remove method for the last single element. It's called [Array.prototype.pop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/pop). If you want to remove chunks of an array at a time, as you mentioned there's [Array.prototype.splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/splice). Not sure why the no bueno, just because it's called `splice` rather than `remove`.

                                Jeremy Falcon

                                Sander RosselS Offline
                                Sander RosselS Offline
                                Sander Rossel
                                wrote on last edited by
                                #46

                                Those aren't remove functions. You forgot shift, which removes the first element. However, I very rarely need to remove the first or last element specifically. If I have a reference to an element I don't even know its index, I just want to be able to remove it. It's just JavaScripts way of saying "it's an array, but you can abuse it as stack or queue." Splice is also something different entirely. You need an index and the number of items you want to remove starting at that index. I can never remember it: array.splice(array.indexOf(something), 1);. It can also be used to add new elements at the designated index, so clearly not a remove. The slice methods just returns a portion of the array between the specified indexes, and it sounds too much like splice to be able to remember clearly which is which. Someone new to JavaScript would never guess what it does or how to use it. I just want to say array.remove(something); and it should remove something. A remove function is easy to remember, easy to use and clearly conveys your intent. I don't care if it just does array.splice(array.indexOf(something), 1); internally, I just want to be rid of that awful syntax. Everyone who says "splice is JavaScripts remove function" is dead wrong.

                                Best, Sander Azure DevOps Succinctly (free eBook) Azure Serverless Succinctly (free eBook) Migrating Apps to the Cloud with Azure arrgh.js - Bringing LINQ to JavaScript

                                J 2 Replies Last reply
                                0
                                • Sander RosselS Sander Rossel

                                  Those aren't remove functions. You forgot shift, which removes the first element. However, I very rarely need to remove the first or last element specifically. If I have a reference to an element I don't even know its index, I just want to be able to remove it. It's just JavaScripts way of saying "it's an array, but you can abuse it as stack or queue." Splice is also something different entirely. You need an index and the number of items you want to remove starting at that index. I can never remember it: array.splice(array.indexOf(something), 1);. It can also be used to add new elements at the designated index, so clearly not a remove. The slice methods just returns a portion of the array between the specified indexes, and it sounds too much like splice to be able to remember clearly which is which. Someone new to JavaScript would never guess what it does or how to use it. I just want to say array.remove(something); and it should remove something. A remove function is easy to remember, easy to use and clearly conveys your intent. I don't care if it just does array.splice(array.indexOf(something), 1); internally, I just want to be rid of that awful syntax. Everyone who says "splice is JavaScripts remove function" is dead wrong.

                                  Best, Sander Azure DevOps Succinctly (free eBook) Azure Serverless Succinctly (free eBook) Migrating Apps to the Cloud with Azure arrgh.js - Bringing LINQ to JavaScript

                                  J Offline
                                  J Offline
                                  Jeremy Falcon
                                  wrote on last edited by
                                  #47

                                  Sander Rossel wrote:

                                  You forgot shift, which removes the first element.

                                  Didn't forget it man. It's an Internet post... not a book. I was giving a few examples. Do better than the kiddie crap on CP.

                                  Sander Rossel wrote:

                                  I just want to say array.remove(something); and it should remove something.

                                  Well that's enough reason to hate an entire language. #sarcasm

                                  Sander Rossel wrote:

                                  Everyone who says "splice is JavaScripts remove function" is dead wrong.

                                  Well, what I find with programmers, they lack enough maturity to not be overly emotional about crap. And they love to hate to feel intelligent or superior (usually the opposite). I'm going to give you three examples that don't require much thought, you'll probably not change your mind at all but it doesn't mean I'm wrong... bias and hate by non-experts is bias and hate after all...

                                  // given this
                                  const data = [1, 2, 3, 4, 5];

                                  // method 1, this is where you complain it takes two calls
                                  delete data[2];
                                  console.log(data.filter(x => x));

                                  // method 2, this is where you complain it's not called "remove"
                                  console.log(data.filter((x, i) => x !== 2));

                                  // original method you didn't even bother to try, this mutates
                                  // let me guess, never read the documentation on it?
                                  data.splice(2, 1);
                                  console.log(data);

                                  Also, keep in mind, C# doesn't have a strong sense of immutability, like JavaScript does. Not that you can't mutate, as given in the examples... I suggest you try running that code before perpetuating the unfounded hate.

                                  Jeremy Falcon

                                  1 Reply Last reply
                                  0
                                  • Sander RosselS Sander Rossel

                                    Those aren't remove functions. You forgot shift, which removes the first element. However, I very rarely need to remove the first or last element specifically. If I have a reference to an element I don't even know its index, I just want to be able to remove it. It's just JavaScripts way of saying "it's an array, but you can abuse it as stack or queue." Splice is also something different entirely. You need an index and the number of items you want to remove starting at that index. I can never remember it: array.splice(array.indexOf(something), 1);. It can also be used to add new elements at the designated index, so clearly not a remove. The slice methods just returns a portion of the array between the specified indexes, and it sounds too much like splice to be able to remember clearly which is which. Someone new to JavaScript would never guess what it does or how to use it. I just want to say array.remove(something); and it should remove something. A remove function is easy to remember, easy to use and clearly conveys your intent. I don't care if it just does array.splice(array.indexOf(something), 1); internally, I just want to be rid of that awful syntax. Everyone who says "splice is JavaScripts remove function" is dead wrong.

                                    Best, Sander Azure DevOps Succinctly (free eBook) Azure Serverless Succinctly (free eBook) Migrating Apps to the Cloud with Azure arrgh.js - Bringing LINQ to JavaScript

                                    J Offline
                                    J Offline
                                    Jeremy Falcon
                                    wrote on last edited by
                                    #48

                                    Also, this is why I post less and less on CP. I can't post anything without someone coming along who knows little about the language and give their hateful opinion on JavaScript. It's a waste of time man, to repeat the same conversation over and over again for years.

                                    Jeremy Falcon

                                    1 Reply Last reply
                                    0
                                    • M Matt Bond

                                      When seeking consistency, I would wrap all of that in a utility class. This way I know it's consistent and works the same everywhere. If I need something a little different, then I either overload or add a default parameter as the occasion requires. I agree that storing the numerator and denominator would be the best way to prevent most headaches. In C#, I would use a Fraction struct for this (home grown if one doesn't exist already). Only collapse the fraction to a primitive type as necessary. This also has the benefit of letting you use money with a decimal value, so you don't have to do the extra math to get the cents back. Speaking of money, you only have to store 4 decimals with money to be accurate for accounting purposes. I deal with fiduciary escrow accounts for my job, and that's all we've every used. Never had a problem being out of balance by a penny in 24 years. However, we don't do multiplication and division on the money. I don't think that would change much though as long as you kept the division and rounding to the end of the math problem.

                                      Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere

                                      J Offline
                                      J Offline
                                      Jeremy Falcon
                                      wrote on last edited by
                                      #49

                                      Matt Bond wrote:

                                      When seeking consistency, I would wrap all of that in a utility class. This way I know it's consistent and works the same everywhere. If I need something a little different, then I either overload or add a default parameter as the occasion requires.

                                      Ultimately, that's what I did. Except they were utility functions because I'm more functional than oop. Same concept though.

                                      Matt Bond wrote:

                                      I agree that storing the numerator and denominator would be the best way to prevent most headaches. In C#, I would use a Fraction struct for this (home grown if one doesn't exist already). Only collapse the fraction to a primitive type as necessary. This also has the benefit of letting you use money with a decimal value, so you don't have to do the extra math to get the cents back.

                                      Yeah, it's an awesome idea. A pretty cool piece of code was posted earlier for rational numbers. My only concern with a language like JavaScript is the speed of that. In something like C/C++ I wouldn't think twice about using it.

                                      Matt Bond wrote:

                                      Speaking of money, you only have to store 4 decimals with money to be accurate for accounting purposes.

                                      Whoops. I was storing 2. Thanks for this. :laugh:

                                      Matt Bond wrote:

                                      However, we don't do multiplication and division on the money.

                                      How do you do arithmetic on it then? Like, to calculate interest then? Thanks for the reply btw.

                                      Jeremy Falcon

                                      M 1 Reply Last reply
                                      0
                                      • L Lloyd Folden 2024

                                        One thing to consider, there is a worldwide standard that most operating systems follow, IEEE 64-BIT. To me it wouldn't be unreasonable to follow that. Anyone situation that requires more would be highly specialized.

                                        J Offline
                                        J Offline
                                        Jeremy Falcon
                                        wrote on last edited by
                                        #50

                                        I'll check it out. Thanks.

                                        Jeremy Falcon

                                        1 Reply Last reply
                                        0
                                        • B Bruce Patin

                                          Financial apps as far as I know use four decimal digits during calculations to avoid problems with only two, then round at the end.

                                          J Offline
                                          J Offline
                                          Jeremy Falcon
                                          wrote on last edited by
                                          #51

                                          Yeah, someone else just posed this. I'm gonna do the same then. Thanks man.

                                          Jeremy Falcon

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups