'Need decimals to round to the nearest integer

I'm using the price adjuster script, but after I run the script I need it to also round to the nearest integer based on if it is .25 and higher, round up and if it is .24 and lower, round down.

Examples:

  • $1,316.10 to become $1,316.00
  • $1,126.28 to become $1,127.00

Is there a way to also only affect a certain character style as well?



Solution 1:[1]

Try this:

var style_name = 'my_style';

// find all the prices
app.findGrepPreferences = NothingEnum.nothing;
app.findGrepPreferences.findWhat = "\\$[\\d,]+\\.\\d+";
var prices = app.activeDocument.findGrep();
if (prices.length == 0) { alert('Nothing was found'); exit() }

// loop through all the finds
var i = prices.length;
while(i--) {

    // skip if the price has another style name
    if (prices[i].appliedCharacterStyle.name != style_name) continue;

    // get the numbers
    var numbers = prices[i].contents.slice(1).replace(/,/g,'').split('.')
    var number_left  = numbers[0];
    var number_right = numbers[1];

    // change the numbers
    if (number_right >= 25) number_left++;
    var rounded_number = '$' + add_commas(number_left) + '.00';

    // replace the price with the rounded number
    prices[i].contents = rounded_number;
}

// function to convert: 12345678 --> "12,345,678"
function add_commas(num) {
    var arr = num.toString().split('');
    var new_arr = [];
    while (arr.length) {
        new_arr.unshift([arr.pop(),arr.pop(),arr.pop()].reverse().join(''));
    }
    return new_arr.join(',');
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RobC