# 使用字符串操作截断整数？Truncating integer using string manipulation?

``````roundUpto2digit(12356463) == 12
roundUpto2digit(12547984) == 13 // The 5 rounds the 12 up to 13.
``````

``````int roundUpto2digit(int cents){
// convert cents to string
string truncatedValue = to_string(cents);
// take first two elements corresponding to the Most Sign. Bits
// convert char to int, by -'0', multiply the first by 10 and sum the second
int totalsum =  int(truncatedValue[0]-'0')*10 + int(truncatedValue[1]-'0');
// if the third element greater the five, increment the sum by one
if (truncatedValue[2]>=5) totalsum++;
return totalsum;
}
``````

## 2 个回复2

### #1楼 票数：1 已采纳

``````ROUNDED_VAL = (INITIAL_VAL + (10^(ORIG_SCALE - 2) / 2)) / 10^(ORIG_SCALE - 2)
``````

``````int roundUpto2digit(int cents){
int scale = 10;
while(cents / scale > 0) {
// Find out original scale. This can be done maybe faster with a divide and conquer algorithm
scale *= 10;
}
int applied_scale = scale / 100;
if (applied_scale == 0) {
// In case there is only one digit, scale it up to two
return 10 * cents;
}
return ((cents + (applied_scale / 2)) / applied_scale);
}
``````

### #2楼 票数：0

``````#include <math.h>

int roundUpto2digit(int value)
{
value /= pow(10,(int)log10(value)-2);
/*
(int)log10(value) returns base ten logarithm (number of digits of your number)
pow(10, N) returns number 1 followed by N zeros
example:
pow(10,(int)log10(123)-2) returns 1
pow(10,(int)log10(1234)-2) returns 10
pow(10,(int)log10(1234567)-2) returns 10000
thus
value / pow(10,(int)log10(value)-2) returns first 3 digits
*/
return value%10>=5? (value+10)/10 : value/10;
/*
if(value%10>=5)// the last digit is >= 5
{
// increase previous number
value = value + 10;
}
// return number without the last digit
return value/10;
*/
}
``````

## 未解决问题？本站智能推荐：

1回复

3回复

2回复

1回复

1回复

### Java中Swifts整数“溢出运算符”&*、&+和&-的等价物是什么？

Swift 为整数运算提供了所谓的“溢出运算符”&*、*+、&-（ Swift 高级运算符）。 它们旨在在执行会导致溢出的操作时截断可用位的数量。 例如： 由于 Java 不支持无符号整数，因此可能没有真正的等价物。 在 Java 8 中，有Integer.toUnsigned
1回复

3回复

2回复