需要小数舍入到最接近的整数
Need decimals to round to the nearest integer
我正在使用价格调整器脚本,但在我 运行 脚本之后,我需要它根据它是否为 .25
或更高舍入到最接近的整数,向上舍入并如果是 .24
及以下,则向下舍入。
示例:
,316.10
变为 ,316.00
,126.28
变成 ,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(',');
}
我正在使用价格调整器脚本,但在我 运行 脚本之后,我需要它根据它是否为 .25
或更高舍入到最接近的整数,向上舍入并如果是 .24
及以下,则向下舍入。
示例:
,316.10
变为,316.00
,126.28
变成,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(',');
}