fix: convert string to int to handle with decimal bigInt (#28384)

* fix: convert string to int to handle with decimal bigInt

Signed-off-by: Wellington Garcia <garciawell@gmail.com>

* fix: change + to Number more readable

Signed-off-by: Wellington Garcia <garciawell@gmail.com>

---------

Signed-off-by: Wellington Garcia <garciawell@gmail.com>
This commit is contained in:
Wellington Garcia
2025-01-17 10:16:42 -03:00
committed by GitHub
parent ac0e1acf78
commit f35a754f48
5 changed files with 46 additions and 4 deletions
@@ -33,6 +33,7 @@ describe('pod', () => {
[10.0, '100'],
[10.1, '100'],
['10', 100.1],
['10.0', 100.1],
])('%p out of %p gives 10%%', (current, resource) =>
expect(currentToDeclaredResourceToPerc(current, resource)).toBe('10%'),
);
+2 -2
View File
@@ -127,10 +127,10 @@ export const currentToDeclaredResourceToPerc = (
}
const numerator: bigint = BigInt(
typeof current === 'number' ? Math.round(current) : current,
typeof current === 'number' ? Math.round(current) : Number(current),
);
const denominator: bigint = BigInt(
typeof resource === 'number' ? Math.round(resource) : resource,
typeof resource === 'number' ? Math.round(resource) : Number(resource),
);
return `${(numerator * BigInt(100)) / denominator}%`;
@@ -0,0 +1,32 @@
import { currentToDeclaredResourceToPerc } from './resources';
/*
* Copyright 2025 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
describe('currentToDeclaredResourceToPerc', () => {
it.each([
[10, 100],
[10, '100'],
['10', 100],
['10', '100'],
['10', 100.0],
[10.0, '100'],
[10.1, '100'],
['10', 100.1],
['10.0', 100.1],
])('should handle with decimal values', (current, resource) =>
expect(currentToDeclaredResourceToPerc(current, resource)).toBe(10),
);
});
@@ -23,8 +23,12 @@ export const currentToDeclaredResourceToPerc = (
return Math.round((current / resource) * 100);
}
const numerator: bigint = BigInt(current);
const denominator: bigint = BigInt(resource);
const numerator: bigint = BigInt(
typeof current === 'number' ? Math.round(current) : Number(current),
);
const denominator: bigint = BigInt(
typeof resource === 'number' ? Math.round(resource) : Number(resource),
);
return Number((numerator * BigInt(100)) / denominator);
};