I am wondering here is that is it a bad idea to implement a legal payment system using JavaScript on the client-side and PHP on the server-side? I am mainly worried about IEEE floating point and overly loose languages.
-
Why it may be a bad idea? Use whatever language your developers are good at. – Vlad Nov 27 '10 at 19:12
-
1Why would IEEE floating point format be a concern? That typically only becomes an issue when working at the assembler level. – 3Dave Nov 27 '10 at 19:18
-
6@David: paste this into your URL bar: javascript:alert(0.2 + 0.1); – Michael Borgwardt Nov 27 '10 at 19:23
3 Answers
The main problem is Javascript, which doesn't even have a real integer type, let alone an (official) proper decimal library (PHP has BC Math). There is an old third-party port of Java's BigDecimal to Javascript you could use on the client side. Alternatively, calculate everything in cents, since an IEEE double can accurately represent integers up to 53 bits in length, which is enough to hold even the entire US sovereign debt for at least another 10 years (probably).

- 342,105
- 78
- 482
- 720
-
3IMHO, the client side doesn't need to calculate anything. (Almost) every calculation should be done at the server side. The JS side should just pass all the user input to the server as strings (perhaps making some simple validations) – Vlad Nov 27 '10 at 19:19
-
@Vlad: That's partly true, but there are cases like when adding custom products to a cart, you don't want to create XHR all the time because they would make the application to be slow. I also have an interface where you go modify the amount of EURs per payment plan and I have seen cases where it did not do very well with JavaScript. – Tower Nov 27 '10 at 19:25
-
thanks for the answer. I think storing values in cents is a good choice. I'll also take a look at the library you have shown. – Tower Nov 27 '10 at 19:28
I would say it depends on how you implement it. Javascript runs on the client side and is therefor not secure. It cannot be trusted. Also, it means your system will not work for people who have Javascript turned off or use older browsers.
As long as you keep that in mind, use the PhP to handle the secure stuff and check everything that comes from the Javascript and are willing to lose those who do not have Javascript, then I don't see a problem with it.
But doing all that can be harder than you would think, so be careful.

- 12,414
- 18
- 67
- 93
The real issue, as others have noted, is that you can't trust the client. Ever. No calculations ought to be done on the client side, or using data (such as price) coming from the client. Beyond that, I would never use a float to represent monetary amounts. Money should always be represented as an integer where 1 represents a single unit of the basic unit of currency (e.g. cents). it complicates matters slightly but do yourself a favor and create some easy accessor functions and your life will be easier for it.

- 4,113
- 23
- 20