Skip to main content
Participating Frequently
January 2, 2024
Answered

Truncate numbers without rounding

  • January 2, 2024
  • 1 reply
  • 1003 views

I have a field that divides a number by 100 and I only want to show two places past the decimal without rounding, would this work for that and would I need to add this to the formula that does the dividing or would this go into a format tab?  

 

Code I was using in the calculate tab:

var grandTotal = +getField("GrandTotal").value;

if (!isNaN(grandTotal) && grandTotal !== 0) {

event.value = grandTotal / 100;
}

Code I was using in the format tab:

event.value = util.printf("%.2f", event.value);

 

Thank you in advance if you can help.

 

This topic has been closed for replies.
Correct answer try67

If you only need to do it once then the full calculation code can be:

 

var grandTotal = Number(this.getField("GrandTotal").value);
if (!isNaN(grandTotal) && grandTotal !== 0) {
	event.value = truncateNumber(grandTotal / 100, 2);
} else event.value = "";

function truncateNumber(v, nDecimals) {
	var re = new RegExp("\\d+\\.\\d{"+nDecimals+"}");
	var results = (""+v).match(re);
	if (results!=null) return results[0];
	else return v;
}

1 reply

try67
Community Expert
Community Expert
January 2, 2024

Don't use the Format tab at all for this.

Instead, you can use this function I wrote in your calculation script:

 

function truncateNumber(v, nDecimals) {
	var re = new RegExp("\\d+\\.\\d{"+nDecimals+"}");
	var results = (""+v).match(re);
	if (results!=null) return results[0];
	else return v;
}

 

If you define it as a doc-level script, change this line in your code:

event.value = grandTotal / 100;

To this:

event.value = truncateNumber(grandTotal / 100, 2);

Participating Frequently
January 3, 2024

I am new to working with JavaScript, so sorry if this is a dumb question but would I use your code as a stand-alone in place of the one I made?

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
January 3, 2024

If you only need to do it once then the full calculation code can be:

 

var grandTotal = Number(this.getField("GrandTotal").value);
if (!isNaN(grandTotal) && grandTotal !== 0) {
	event.value = truncateNumber(grandTotal / 100, 2);
} else event.value = "";

function truncateNumber(v, nDecimals) {
	var re = new RegExp("\\d+\\.\\d{"+nDecimals+"}");
	var results = (""+v).match(re);
	if (results!=null) return results[0];
	else return v;
}