Closed (fixed)
Project:
Format Number API
Version:
6.x-1.x-dev
Component:
Code
Priority:
Normal
Category:
Feature request
Assigned:
Unassigned
Reporter:
Created:
7 Sep 2009 at 04:21 UTC
Updated:
9 Nov 2011 at 10:22 UTC
I'm doing calculations on currency values, and the cents weren't adding up. When forcing to 2 decimal places, this code is simply dropping additional decimals, instead of rounding up. I've implemented a quick work-around:
--- modules/format_number/format_number.js (revision 14610)
+++ modules/format_number/format_number.js (working copy)
@@ -14,6 +14,8 @@
* The formatted number.
*/
Drupal.formatNumber = function(number, decimals) {
+ var rounded = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
+
if (typeof(number) != "number") {
number = 0;
}
@@ -44,6 +46,8 @@
// Build the decimal part of the number.
if (decimals > 0) {
+ number_parts = (Math.abs(rounded) + "").split(".");
+
var decimal_part = (number_parts.length <= 1 ? "0" : number_parts[1]);
if (decimal_part.length > decimals) {
decimal_part = decimal_part.substr(0, decimals);
Comments
Comment #1
markus_petrux commentedOut of curiosity, are you using Drupal.formatNumber() in custom code or through Formatted Number CCK?
I'm asking because I was truncating because when used for a form element, it seemed to me the most logical way to behave. So maybe we need to add a 3rd argument to Drupal.formatNumber() to tell if we want the result truncated of rounded. Truncated would have to be default.
Comment #2
markus_petrux commentedComment #3
jonathan_hunt commentedIn this case I'm using it via the js API in custom code (I'm doing some client side order calculations, but want formatting like thousands separator and dollars, cents). Yep, an additional process argument might be needed, defaulting to truncated.
Comment #4
markus_petrux commentedOk, thanks. So, let's mark this issue as needs work, and I'll work on it later today or tomorrow if you haven't already.
Comment #5
markus_petrux commentedBetter title.
Comment #6
markus_petrux commentedComment #7
markus_petrux commentedCould you please try the following patch?
Comment #8
markus_petrux commentedCommitted to CVS. Thanks!
http://drupal.org/cvs?commit=265106
Comment #10
hanno commentedThis patch has changed the optional behavior of formatnumber.js, but not for function format_number($number), right?
Also, shouldn't round be the expected default for numbers? (like in Excel, Numbers and the default cck number)