I'm stuck in a javascript code, which gives me wrong result, can anyone help me please

syd1980

14-09-2020

Hello folks,

Below is the JavaScript code for three fields 1- SubTotal 2- Actual VAT 3- VAT (this is the VAT result as per our requirement), everything is working fine whenever I'm giving any amount in the subtotal field it gives me the correct result without rounding off with 2 decimals. except for two number 41 & 51, with these two numbers, I suppose to get "2.05" and "2.55" respectively but the result what I'm getting with the below code are "2.04" & "2.54", unable to understand why. Is something wrong with my code? Could you please help me in solving this?

 

temp1 = VATnew.rawValue * 100;
//app.alert("temp1: " + temp1);
//convert to int. to drop remaining decimals
temp2 = parseInt(temp1);
//app.alert("temp2: " + temp2);
// divide by 100 to shift back 2 places
temp3 = temp2 / 100;
//app.alert("temp3: " + temp3);

// return data to field
this.rawValue = temp3;

VAT Result.jpg

 

 

 

Accepted Solutions (0)

Answers (3)

Answers (3)

Kosta_Prokopiu

15-09-2020

Here we try a completely different approach

The third field is a Text Field as the result is a manipulated string

Kosta_Prokopiu_0-1600206632435.png

Set the pattern of the second field as shown here

Kosta_Prokopiu_3-1600207280996.png

 

Kosta_Prokopiu_1-1600206707550.png

The calculate script

function toFixed(num, fixed) {
var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
return num.toString().match(re)[0];
}
toFixed(NumericField2.formattedValue,2)

No unpredictable rounding with this one...

Check if you find any values where this does not work...

Kosta_Prokopiu_2-1600207232223.png

 

Kosta_Prokopiu

14-09-2020

This seems to work - check it out

Kosta_Prokopiu_0-1600102255149.png

I guess 5% VAT?

Kosta_Prokopiu_1-1600102331012.pngKosta_Prokopiu_2-1600102375376.png

function truncate(number)
{
if (number > 999) {
return number > 0
? Math.floor(number)
: Math.ceil(number);
} else {
return number;
}
}

Kosta_Prokopiu_3-1600102542860.png

 

 

radzmar

MVP

14-09-2020

The parseInt() method has a second parameter called radix. Its used the define the number base, for decimals its 10.

You should use it to avoid that the input is converted into a wrong number by assuming the wrong base.

parseInt(temp1, 10);