I'm working on a project that involves manipulating cryptocurrency prices in JavaScript. I'm trying to write a function that can adjust the decimal points of a number, and then add or subtract a specified amount from that number. For example, if the input number is "27055.95" and I want to add "1" to it, the result should be "27055.96". If the input number is "26973.9" and I want to add "1" to it, the result should be "26974.0".
I've written a function that can perform the addition or subtraction, but I'm having trouble adjusting the decimal points of the input number. Here's what I have so far:
function adjustPrice(priceString, increaseAmount) {
const price = parseFloat(priceString);
const newPrice = price + increaseAmount;
// TODO: Adjust decimal points of newPrice
return newPrice.toString();
}
console.log(adjustPrice("27055.95", 1)); // Expected output: "27055.96"
console.log(adjustPrice("27055.99", 1)); // Expected output: "27056.0"
console.log(adjustPrice("27055.00", -1)); // Expected output: "27054.99"
console.log(adjustPrice("26973.9", 1)); // Expected output: "26974.0"
console.log(adjustPrice("269", 1)); // Expected output: "270"
How can I modify this function to adjust the decimal points of newPrice so that it matches the desired output format? I want the function to add or subtract increaseAmount from price, and then adjust the decimal points of the result to match the input format. For example, if the input format is "27055.95", I want the output format to be "27055.96" if I add "1" to it, and "27055.94" if I subtract "1" from it. Is there a built-in JavaScript method or library that can help me achieve this? If not, what is the most efficient way to perform this operation?
I've also tried using the "big.js" library to perform this operation, but I'm having trouble getting the expected output. Here's what I've tried:
const Big = require('big.js');
function adjustPrice(priceString, increaseAmount) {
const bigPrice = new Big(priceString);
const bigIncreaseAmount = new Big(increaseAmount);
const newPrice = bigPrice.plus(bigIncreaseAmount);
// TODO: Adjust decimal points of newPrice
return newPrice.toString();
}
const regexp = /^\d+(\.(?<decimals>\d+))?$/;
function adjustPrice(priceString, adjustment) {
const match = priceString.match(regexp);
if (!match) throw new Error("Unexpected input format");
const decimals = match.groups.decimals?.length ?? 0;
const factor = 10 ** (decimals * -1);
const price = Number(priceString);
const adjustedPrice = adjustment * factor + price;
return adjustedPrice.toFixed(decimals);
}
for (
const [input, adjustment, expected] of [
["27055.95", 1, "27055.96"],
["27055.99", 1, "27056.00"],
["27055.00", -1, "27054.99"],
["26973.9", 1, "26974.0"],
["269", 1, "270"],
]
) {
const actual = adjustPrice(input, adjustment);
console.log(
actual === expected ? "✅" : "❌",
`(${input}, ${adjustment})`,
"->",
actual,
);
}
Lastly: Beware the perhaps unintuitive consequences of floating point math: 1, 2