需要小数才能四舍五入到最接近的整数



我使用的是价格调整器脚本,但在运行该脚本后,我还需要它使用以下逻辑四舍五入到最接近的整数:如果小数部分是.25或更高,则向上取整,否则向下取整。

示例:

  • $1,316.10变为$1,316.00
  • $1,126.28变为$1,127.00

有没有办法也只影响特定的角色风格?

试试这个:

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(',');
}

最新更新