66 lines
2.1 KiB
TypeScript
66 lines
2.1 KiB
TypeScript
export function roundToWholeNumber(value: number): number {
|
|
return Math.round(value);
|
|
}
|
|
|
|
export function roundToDecimalPlaces(value: number, places: number): number {
|
|
const factor = Math.pow(10, places);
|
|
return Math.round(value * factor) / factor;
|
|
}
|
|
|
|
export function roundToSignificantFigures(value: number, sigFigs: number): number {
|
|
if (value === 0) return 0;
|
|
const magnitude = Math.floor(Math.log10(Math.abs(value)));
|
|
const factor = Math.pow(10, sigFigs - 1 - magnitude);
|
|
return Math.round(value * factor) / factor;
|
|
}
|
|
|
|
export function toStandardForm(value: number): { coefficient: number; exponent: number } {
|
|
if (value === 0) return { coefficient: 0, exponent: 0 };
|
|
const exponent = Math.floor(Math.log10(Math.abs(value)));
|
|
const coefficient = value / Math.pow(10, exponent);
|
|
return {
|
|
coefficient: roundToDecimalPlaces(coefficient, 10),
|
|
exponent,
|
|
};
|
|
}
|
|
|
|
export function fromStandardForm(coefficient: number, exponent: number): number {
|
|
return coefficient * Math.pow(10, exponent);
|
|
}
|
|
|
|
export function compareDecimals(a: number, b: number): -1 | 0 | 1 {
|
|
if (a > b) return 1;
|
|
if (a < b) return -1;
|
|
return 0;
|
|
}
|
|
|
|
export function getPlaceValue(value: number): { digit: number; place: string }[] {
|
|
const places = [
|
|
"thousands", "hundreds", "tens", "units", "tenths", "hundredths", "thousandths",
|
|
];
|
|
const str = Math.abs(value).toFixed(3);
|
|
const [intPart, decPart] = str.split(".");
|
|
const paddedInt = intPart.padStart(4, "0");
|
|
const result: { digit: number; place: string }[] = [];
|
|
|
|
for (let i = 0; i < 4; i++) {
|
|
result.push({ digit: parseInt(paddedInt[i]), place: places[i] });
|
|
}
|
|
for (let i = 0; i < 3; i++) {
|
|
result.push({ digit: parseInt(decPart[i]), place: places[4 + i] });
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export function multiplyByPowerOf10(value: number, power: number): number {
|
|
return roundToDecimalPlaces(value * Math.pow(10, power), 10);
|
|
}
|
|
|
|
export function divideByPowerOf10(value: number, power: number): number {
|
|
return roundToDecimalPlaces(value / Math.pow(10, power), 10);
|
|
}
|
|
|
|
export function standardFormToKatex(coefficient: number, exponent: number): string {
|
|
return `${coefficient} \\times 10^{${exponent}}`;
|
|
}
|